Ice*_*lin 3 python lambda pandas
在 Pandas 数据框中使用 Lambda 时,如何正确引用另一个列值。
dfresult_tmp2['Retention_Rolling_temp'] = dfresult_tmp2['Retention_tmp'].apply(lambda x: x if x['Count Billings']/4 < 0.20 else '')
Run Code Online (Sandbox Code Playgroud)
上面的代码给了我这个错误。
TypeError: 'float' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)
dfresult_tmp2['Retention_tmp'].apply(
lambda x: x if x['Count Billings'] / 4 < 0.20 else ''
)
Run Code Online (Sandbox Code Playgroud)
您正在使用pd.Series.apply的不同于pd.DataFrame.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, '')
Run Code Online (Sandbox Code Playgroud)
选项 2
np.where
r = dfresult_tmp2['Retention_tmp'].values
b = dfresult_tmp2['Count Billings'].values
dfresult_tmp2['Retention_tmp'] = np.where(b / 4 < .2, r, '')
Run Code Online (Sandbox Code Playgroud)
选项 3
您要求的但不是我推荐的。
apply
dfresult_tmp2['Retention_tmp'] = dfresult_tmp2.apply(
lambda x: x['Retention_tmp'] if x['Count Billings'] / 4 < .2 else '',
axis=1
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4272 次 |
| 最近记录: |