gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:38:30 25 4
gpt4 key购买 nike

我正在尝试创建一个新列,如果“性别”为“女性”,则将“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com