我有一个按日期和ID索引的pandas数据帧。我想:
date ID value
12/31/2010 13 -0.124409
9 0.555959
1 -0.705634
2 -3.123603
4 0.725009
1/31/2011 13 0.471078
9 0.276006
1 -0.468463
22 1.076821
11 0.668599
期望的输出:
date ID flag
1/31/2011 22 addition
1/31/2011 11 addition
1/31/2011 2 deletion
1/31/2011 4 deletion
我试过Diff between two dataframes in pandas 。我不能让这个在分组数据框架上工作。我不确定如何循环每个组,并与之前的组进行比较。
答案 0 :(得分:1)
您可以使用duplicated
来查找不同的值
s=df[~df.index.get_level_values(1).duplicated(keep=False)]
pd.DataFrame({'date':['1/31/2011']*len(s),'ID':s.index.get_level_values(1),'flag':(s.index.get_level_values(0)=='1/31/2011')}).replace({False:'deletion',True:'addition'})
Out[529]:
ID date flag
0 2 1/31/2011 deletion
1 4 1/31/2011 deletion
2 22 1/31/2011 addition
3 11 1/31/2011 addition
答案 1 :(得分:0)
我创建了一个辅助函数,它可以移动pandas.MultiIndex
的第一级。有了这个,我可以将它与原始索引区分开来,以确定添加和删除。
def shift_level(idx):
level = idx.levels[0]
mapping = dict(zip(level[:-1], level[1:]))
idx = idx.set_levels(level.map(mapping.get), 0)
return idx[idx.get_level_values(0).notna()].remove_unused_levels()
idx = df.index
fidx = shift_level(idx)
additions = fidx.difference(idx)
deletions = idx[idx.labels[0] > 0].difference(fidx)
pd.Series('+', additions).append(
pd.Series('-', deletions)).rename('flag').reset_index()
date ID flag
0 2011-01-31 2 +
1 2011-01-31 4 +
2 2011-01-31 11 -
3 2011-01-31 22 -