【发布时间】:2016-02-20 05:34:17
【问题描述】:
如何在pandas 中对正负值进行不同的求和并将它们放在positive 和negative 列中?
我有如下数据框:
df = pandas.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C' : np.random.randn(8), 'D' : np.random.randn(8)})
输出如下:
df
A B C D
0 foo one 0.374156 0.319699
1 bar one -0.356339 -0.629649
2 foo two -0.390243 -1.387909
3 bar three -0.783435 -0.959699
4 foo two -1.268622 -0.250871
5 bar two -2.302525 -1.295991
6 foo one -0.968840 1.247675
7 foo three 0.482845 1.004697
我使用下面的代码得到否定:
df['negative'] = df.groupby('A')['C'].apply(lambda x: x[x<0].sum()).reset_index()]
但问题是,当我想将它添加到名为 negative 的 dataframe 列之一时,它会给出错误:
ValueError: Wrong number of items passed 2, placement implies 1
我再次知道groupby 已返回多个列并且无法将其分配给df['negatives'] 的内容,但我不知道如何解决这部分问题。我也需要有积极的col。
期望的结果是:
A Positive Negative
0 foo 0.374156 -0.319699
1 bar 0.356339 -0.629649
什么是问题的正确解决方案?
【问题讨论】:
标签: python pandas group-by sum dataframe