我有一个数据帧,在清理和合并之后,它最终处于多行具有相同索引值的状态。
我需要合并这些重复的行并得到一个数据框,其中每次运行的重复项都有一行。
这感觉应该是使用数据帧时的标准操作,但我似乎无法弄清楚如何让 Pandas 做到这一点。
我找到的最佳答案在这里:Merge two rows in the same Dataframe if their index is the same?
但是,那里提出的解决方案最终以“groupby”对象而不是数据框结束。因为我想在框架上进行进一步的分组,所以我不知道如何继续。
pandas 中的方法是否有一个标准函数,用于压缩多行共享相同索引的数据帧,并返回一个新的数据帧?
例如:
visits revenue product-type
product1 200 50 stockings
product1 50 100 #n/a
product2 150 20 toy
... .. .. ..
至
visits revenue product-type
product1 250 150 stockings
product2 150 20 toy
... .. .. ..
最佳答案
您可以groupby
通过 index
然后 aggregate
:
print (df.groupby(level=0).agg({'visits':sum,'revenue':sum,'product-type':'first'}))
visits revenue product-type
product1 250 150 stockings
product2 150 20 toy
最后一列的更好功能可能是 join
- 您的数据不会丢失,( first
仅采用第一个值,其他数据将被删除):
print (df.groupby(level=0).agg({'visits':sum,
'revenue':sum,
'product-type': lambda x: ''.join(x.fillna(''))}))
visits revenue product-type
product1 250 150 stockings
product2 150 20 toy
如果仅使用sum
,则最后一列将被删除 - automatic exclusion of nuisance columns :
print (df.groupby(level=0).sum())
visits revenue
product1 250 150
product2 150 20
关于python-3.x - 合并数据框中的重复索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37836553/