python正在添加2个具有特定列的数据帧
我有两个数据帧,一个看起来像这样:python正在添加2个具有特定列的数据帧,python,pandas,Python,Pandas,我有两个数据帧,一个看起来像这样: Date id name amount period 2011-06-30 1 A 10000 1 2011-06-30 2 B 10000 1 2011-06-30 3 C 10000 1 id amount period 1 10000
Date id name amount period
2011-06-30 1 A 10000 1
2011-06-30 2 B 10000 1
2011-06-30 3 C 10000 1
id amount period
1 10000 1
3 10000 0
id amount period
1 20000 2
2 10000 1
3 20000 1
另一个是这样的:
Date id name amount period
2011-06-30 1 A 10000 1
2011-06-30 2 B 10000 1
2011-06-30 3 C 10000 1
id amount period
1 10000 1
3 10000 0
id amount period
1 20000 2
2 10000 1
3 20000 1
我想要的结果如下:
Date id name amount period
2011-06-30 1 A 10000 1
2011-06-30 2 B 10000 1
2011-06-30 3 C 10000 1
id amount period
1 10000 1
3 10000 0
id amount period
1 20000 2
2 10000 1
3 20000 1
如何在python中实现这一点?使用聚合sum
的过滤列:
df = pd.concat([df1[['id','amount','period']], df2]).groupby('id', as_index=False).sum()
print (df)
id amount period
0 1 20000 2
1 2 10000 1
2 3 20000 1
编辑:
如果需要减去id
为id
创建索引,然后使用:
但是如果我有其他的计算方法,比如减法或者其他什么?