gpt4 book ai didi

python - 如何计算一行中的条件?

转载 作者:行者123 更新时间:2023-12-01 04:47:17 24 4
gpt4 key购买 nike

我有一个 pandas 数据框:

df = pd.DataFrame({
'a': [1, 2, 0, 3],
'b': [1, 2, 0, 0],
'c': [5, 2, 0, 3],
'd': [0, 3, 7, 1]
})

我现在想创建另一个列 n 来计算列 ['a', 'b', 'c', 'd'] 的值数量是 > 0

我们需要手工做:

df['n'] = [3, 2, 3, 3]

我不需要声明这对于较大的框架来说是不方便的。我知道我们可以选择我们感兴趣的行 df.a > 0, ..., df.d > 0

不幸的是,我无法将提供的 bool 值转换为 01 并对它们求和。

df['n'] = df. a > 0 + df.b > 0 + df.c > 0 + df.d > 0

抛出

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

我该如何纠正这个问题?

最佳答案

您可以执行列表理解,循环遍历列,然后对该列使用 bool 条件,删除不满足条件的值并调用计数:

In [360]:

[df.loc[df[col]>0,col].dropna().count() for col in df]
Out[360]:
[3, 2, 3, 3]

这将产生该列:

In [361]:

df['n'] = [df.loc[df[col]>0,col].dropna().count() for col in df]
df
Out[361]:
a b c d n
0 1 1 5 0 3
1 2 2 2 3 2
2 0 0 0 7 3
3 3 0 3 1 3

在此阶段,将行标记为列名称可能是有意义的,这样您的 n 才有意义。

编辑

我在去吃午饭的路上意识到有一个更简单的方法,只需调用 count :

In [365]:

df[df>0].count()
Out[365]:
a 3
b 2
c 3
d 3
dtype: int64

关于python - 如何计算一行中的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29166314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com