我在pandas数据帧中有一个索引,它重复索引值。我想重新索引为多索引,其中重复索引被分组。
索引看起来像这样:
所以我希望所有112335586索引值在索引中分组相同。
我已经看过这个问题Create pandas dataframe by repeating one row with new multiindex但是这里的值可以是索引可以预先定义,但这是不可能的,因为我的数据帧太大而不能硬编码。
我还查看了多索引文档,但这也预先定义了索引的值。
我相信你需要:
s = pd.Series([1,2,3,4], index=[10,10,20,20])
s.index.name = 'EVENT_ID'
print (s)
EVENT_ID
10 1
10 2
20 3
20 4
dtype: int64
s1 = s.index.to_series()
s2 = s1.groupby(s1).cumcount()
s.index = [s.index, s2]
print (s)
EVENT_ID
10 0 1
1 2
20 0 3
1 4
dtype: int64
试试这个:
df.reset_index(inplace=True)
df['sub_idx'] = df.groupby('EVENT_ID').cumcount()
df.set_index(['EVENT_ID','sub_idx'], inplace=True)