if else的lambda函数

2024-05-20 00:38:15 发布

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

我有一个数据帧,看起来像:

A   B   C   D   SUM 
2   5   -4  12  15

我试着跑:

df.apply((lambda x: x / x.sum() if x/x.sum() >= 0 else None), axis=1).fillna(0)

要得到,如果单元格总数相同,则计算x/总数:

A         B     C   D
2/15    5/15    0   12/15

我得到:

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

如何改进代码。你知道吗


Tags: the数据lambdanonedfifvalueelse
1条回答
网友
1楼 · 发布于 2024-05-20 00:38:15

你把^{}^{}搞混了。它们是不同的方法:一种对一个系列进行操作,对每个元素进行操作;另一种沿着一个轴跨数据帧进行操作。在后一种情况下,沿着axis=1意味着每个被顺序地馈送到函数。你知道吗

因为这些apply方法(两个版本)都是隐蔽的循环,所以每次按列lambda调用之后,数据帧都会发生变化。因此,您需要使用数据帧的副本:

df2 = df.copy()

for col in df.columns[:-1]:
    df2[col] = df.iloc[:, :-1].apply(lambda x: x[col] / x.sum() if x[col]/x.sum() >= 0 \
                                     else None, axis=1).fillna(0)

print(df2)

          A         B  C    D  SUM
0  0.133333  0.333333  0  0.8   15

然而,这一切都是非常低效的。我们没有使用底层NumPy数组。相反,可以使用矢量化操作:

res = df.iloc[:, :-1].div(df.iloc[:, :-1].sum(1), axis=0)
res.mask(res < 0, 0, inplace=True)

print(res)

          A         B    C    D
0  0.133333  0.333333  0.0  0.8

相关问题 更多 >