Lambda数据帧引用另一列中的值

2024-04-25 04:43:22 发布

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

在pandas数据帧中使用Lambda时,如何正确引用另一列值。在

dfresult_tmp2['Retention_Rolling_temp'] = dfresult_tmp2['Retention_tmp'].apply(lambda x: x if x['Count Billings']/4 < 0.20 else '')

上面的代码给出了这个错误。在

^{pr2}$

Tags: 数据lambdapandasifcounttempelsetmp
1条回答
网友
1楼 · 发布于 2024-04-25 04:43:22
dfresult_tmp2['Retention_tmp'].apply(
    lambda x: x if x['Count Billings'] / 4 < 0.20 else ''
)

您使用的是与pd.DataFrame.apply不同的pd.Series.apply。在本例中,您将迭代地向lambda传递一个标量值。所以some_scalar_x['Count Billings']没有意义。在

我将向您展示矢量化版本,而不是告诉您如何将逻辑压缩成apply

选项1
pd.Series.where

dfresult_tmp2['Retention_tmp'] = \
    dfresult_tmp2['Retention_tmp'].where(
        dfresult_tmp2['Count Billings'] / 4 < .2, '')

选项2
np.where

^{pr2}$

选项3
apply
你要的不是我推荐的。在

dfresult_tmp2['Retention_tmp'] = dfresult_tmp2.apply(
    lambda x: x['Retention_tmp'] if x['Count Billings'] / 4 < .2 else ''
)

相关问题 更多 >