使用逻辑运算符创建新列

问题描述 投票:0回答:1

[我正在尝试创建一个新列,以其他列作为输入来分配'五个或更多','-五个或更少','五个到-五个之间:

df['Change']
Out[196]: 
0       -0.398010
1       -3.980227
2        1.475952
3        0.000000
4       -2.043446

31514         NaN
31515         NaN
31516         NaN
31517         NaN
31518         NaN
Name: Change, Length: 30811, dtype: float64

我尝试过:

df['new_column'] = df.apply(lambda x: 'Five Or More' if (df['Change'] >= 5) else 'Between Five And Minus Five')
df['new_column'] = df.apply(lambda x: 'Minus Five Or Less' if (df['Change'] <= 5) else 'Between Five And Minus Five')

对于两个我都遇到此错误:

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

感谢任何帮助!

python pandas apply add
1个回答
0
投票

尝试一下

df['new_column'] = df["Change"].apply(lambda x: 'Five Or More' if (x>= 5) else 'Between Five And Minus Five')
df['new_column'] = df["Change"].apply(lambda x: 'Minus Five Or Less' if (x <= 5) else 'Between Five And Minus Five')
© www.soinside.com 2019 - 2024. All rights reserved.