当值是序列或数据帧时,python apply(lambda x:…)函数应用于字典值

2024-04-23 15:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图对作为数据帧的字典值使用apply(lambda x:…)函数,但得到的是ValueError:序列的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all()。我知道这在dataframe列上有效。但我想知道是否有一种方法可以在字典值上使用它。我做错了什么

import pandas as pd
df = pd.DataFrame({'Gender':['M','M','M','F','F','O1','O2'],
                   'A1':[2,4,8,7,6,4,5],'A2':[2,4,8,7,6,4,5],
                   'B1':[5,8,9,7,5,6,3]})
df
#>   Gender  A1  A2  B1
0      M   2   2   5
1      M   4   4   8
2      M   8   8   9
3      F   7   7   7
4      F   6   6   5
5     O1   4   4   6
6     O2   5   5   3
    
dct = {}
for cat in ['Gender','A','B']:
    dct[cat] = df[[c for c in df.columns if c.startswith(cat)]]
dct
#> {'Gender':   Gender
 0      M
 1      M
 2      M
 3      F
 4      F
 5     O1
 6     O2,
 'A':    A1  A2
 0   2   2
 1   4   4
 2   8   8
 3   7   7
 4   6   6
 5   4   4
 6   5   5,
 'B':    B1
 0   5
 1   8
 2   9
 3   7
 4   5
 5   6
 6   3}

## apply
g = dct['Gender'].apply(lambda x: 'Other' if x not in ['M','W'] else x]

#> ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

所需输出

  Gender
0      M
1      M
2      M
3      F
4      F
5     Other
6     Other

问题:

  1. 如何将apply(lambda x:…)函数传递给字典键的值(它是一个系列或数据帧列)? 能做到吗

Tags: 数据lambdaina2df字典a1gender
3条回答

你可以试试

dct['Gender']['Gender'].apply(lambda x: 'Other' if x not in ['M','W'] else x)
# Output:
0        M
1        M
2        M
3    Other
4    Other
5    Other
6    Other
Name: Gender, dtype: object

dct['Gender']作为一个整体访问该值(这里是一个数据帧)

type(dct['Gender'])
#> pandas.core.frame.DataFrame

dct['Gender']['Gender']访问数据帧中作为值的列。然后,就可以对其使用apply()函数

type(dct['Gender']['Gender'])
#> pandas.core.series.Series

文档:
pandas.Series.apply
对系列的值调用函数

我无法使用Ch3steR答案中的fullmatch一行解决方案(可能是不同的版本?)

df.loc[~df.Gender.isin(['M', 'F']),'Gender'] = 'Others'

您可以在这里直接使用^{}。熊猫对它们有许多可利用的杠杆作用

m = df['Gender'].str.fullmatch(r'[^MF]')
df.loc[m, 'Gender'] = 'Other'

print(df)
#   Gender  A1  A2  B1
# 0      M   2   2   5
# 1      M   4   4   8
# 2      M   8   8   9
# 3      F   7   7   7
# 4      F   6   6   5
# 5  Other   4   4   6
# 6  Other   5   5   3
  • 有关正则表达式模式^{} in ^{}的详细信息

相关问题 更多 >