我试图对 DataFrame 的两列求和以创建第三列,其中第三列中的值等于其他列的正元素的总和。我尝试了下面的方法,只收到一列 NaN 值
df = pd.DataFrame(np.array([[-1, 2], [-2, 2], [1, -3], [1, -4], [ -2 , -2]]),
columns=['a', 'b'])
df['Sum of Positives'] = 0
df['Sum of Positives'] = df.loc[df.a > 0 ,'a'] +df.loc[df.b >0 , 'b']
数据框:最佳答案
您可以使用 df.mask
在这里填充小于 0 的值,即用 0 负值,然后做 df.sum
超过轴 1。
df['sum of pos'] = df.mask(df<0, 0).sum(axis=1)
a b sum of pos
0 -1 2 2
1 -2 2 2
2 1 -3 1
3 1 -4 1
4 -2 -2 0
很少有 NumPy hack 在这里有用。np.copyto
t = np.copy(df.values)
np.copyto(t, 0, where=df.values<0)
df['sum of pos'] = t.sum(axis=1)
np.where
df['sum of pos'] = np.where(df.values<0, 0, df.values).sum(axis=1)
np.clip
df['sum of pos'] = np.clip(df.values, 0, None).sum(axis=1)
np.ma.array
m = np.ma.array(df.values, mask=df.values<0, fill_value=0)
df['sum of pos'] = m.filled().sum(axis=1)
关于python - 如何根据多列的条件在 Pandas 中创建列的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64835098/