python - 应用和 Lambda 函数 - ValueError : The truth value of a Series is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

标签 python pandas dataframe lambda apply

我正在尝试创建一个新列,如果“性别”为“女性”,则将“ID”值除以 219,如果“性别”为“男性”,则使用 Apply 和 Lambda 函数将其除以 393。首先,我尝试使用“性别”列,该列具有不起作用的分类变量。所以我创建了一个基于“性别”的二进制列,将 0 分配给“女性 1”到“男性”并使用该列,但没有用。
我仍然收到这样的值错误:

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


我的代码是
by_label_out_degree[NormID] = by_label_out_degree.apply(lambda row: row['ID']/ 219 if row['Gender2'] == 0 else row['ID']/ 393,axis=1)
我再次添加我的代码!感谢您的帮助!!
values = [
[42785,428855,'Energy','Female'],
[43432,428686,'Trust','Male'],
[43432,428686,'Career','Male'],
[43432,428686,'Personal','Male'],
[43432,428634,'Trust','Female']
]
df: pd.DataFrame = pd.DataFrame(values, columns =['ID','Target','Label','Gender'])
new_df = df.groupby(['Gender','Label']).ID.count().reset_index()
new_df['Gender2'] = new_df.Gender.map({'Female':0,'Male':1})
new_df['NormID'] = new_df.apply(lambda row: row['ID']/219 if row['Gender2'] == 0 else row['ID']/393, axis = 1)

最佳答案

使固定
使用专栏Gender很好用

values = [
    ['Female', 'Access', 96],
    ['Female', 'Career', 165],
    ['Male', 'Access', 236],
    ['Male', 'Energy', 445]
]
df: pd.DataFrame = pd.DataFrame(values, columns=['Gender', 'Label', 'ID'])
df['newcol'] = df.apply(lambda row: row['ID'] / 219 if row['Gender'] == 'Female' else row['ID'] / 393, axis=1)
print(df)

   Gender   Label   ID    newcol
0  Female  Access   96  0.438356
1  Female  Career  165  0.753425
2    Male  Access  236  0.600509
3    Male  Energy  445  1.132316
更好的
使用 numpy.where
import numpy as np
import pandas as pd

values = [['Female', 'Access', 96], ['Female', 'Career', 165],
          ['Male', 'Access', 236], ['Male', 'Energy', 445]]
df: pd.DataFrame = pd.DataFrame(values, columns=['Gender', 'Label', 'ID'])
df['newcol'] = np.where(df['Gender'] == 'Female', df['ID'] / 219, df['ID'] / 393)
print(df)

关于python - 应用和 Lambda 函数 - ValueError : The truth value of a Series is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67618078/

相关文章:

python - 如何在 matplotlib 中使用时间序列绘制各个行值

python - Pandas 匹配多列模式

python - 将 pandas.DataFrame 转换为字节

python - 自修复 Python 线程

python - 使用 Python 3.4 的 Scrapy 在终端中失败

Python Pandas - 读取包含多个表的 csv 文件

python - Pandas:计算两行之间的百分比并将该值添加为一列

python - 为什么我不能将文件目录存储在变量中以与 csv.reader(file()) 一起使用?

python - 如何在特定子字符串之后获取字符串?

r - 使用 dplyr 按最后一列对数据框进行排序