使用逻辑运算符创建新列

2024-06-26 13:24:30 发布

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

我正在尝试创建一个新列,该列将分配“五或更多”、“负五或更少”、“介于五和负五之间”,并将另一列作为其输入:

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().

感谢所有帮助过你的人


Tags: orandlambdadfnewifcolumnbetween
2条回答

更改为此以修复lambda函数

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

在lambda函数中,如果设置lambda x,则需要使用x,并且apply需要位于列上,而不是df本身。查看此以了解更多信息https://datatofish.com/if-condition-in-pandas-dataframe/

另一种方法是创建一个条件函数,并将此函数应用于数据帧,如下所示:

def conditions(x):
    if(x>=5):
        return 'Five or More'
    elif(x<=-5):
        return 'Minus Five or Less'
    else:
        return 'Between Five And Minus Five'

df['new_column'] = df['Change'].apply(conditions)

试试这个

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')

相关问题 更多 >