微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python – 多列上的Lambda函数

我有一个pandas数据框,我更喜欢使用lambda函数而不是循环来解决我的问题.

问题是这样的;

df = pd.DataFrame({'my_fruits':['fruit', 'fruit', 'fruit', 'fruit', 'fruit'],
         'fruit_a': ['apple', 'banana', 'vegetable', 'vegetable', 'cherry'],
         'fruit_b': ['vegetable', 'apple', 'vegeatble', 'pineapple', 'pear']})

如果我应用以下循环;

for i in np.arange(0,len(df)):
    if df['fruit_a'][i] == 'vegetable' or df['fruit_b'][i] == 'vegetable':
        df['my_fruits'][i] = 'not_fruit'

我能够得到我想要的结果.这是因为如果fruit_a或fruit_b列中的任何一个包含值vegetables,我希望my_fruits列等于not_fruit.

我怎样才能在lamda函数中设置它.无法理解两列输入​​如何用于更改不同的列值.谢谢!

解决方法:

您可以通过布尔掩码使用Series.mask

mask = (df['fruit_a'] == 'vegetable') | (df['fruit_b'] == 'vegetable')
print (mask)
0     True
1    False
2     True
3     True
4    False
dtype: bool


df.my_fruits = df.my_fruits.mask(mask, 'not_fruits')
print (df)
     fruit_a    fruit_b   my_fruits
0      apple  vegetable  not_fruits
1     banana      apple       fruit
2  vegetable  vegetable  not_fruits
3  vegetable  pineapple  not_fruits
4     cherry       pear       fruit

掩码的另一个解决方案是通过vegetable比较所有选定的列,然后在any之前至少在一列中获得所有True:

print ((df[['fruit_a', 'fruit_b']] == 'vegetable'))
  fruit_a fruit_b
0   False    True
1   False   False
2    True    True
3    True   False
4   False   False

mask = (df[['fruit_a', 'fruit_b']] == 'vegetable').any(axis=1) 
print (mask)
0     True
1    False
2     True
3     True
4    False
dtype: bool

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐