我需要重新索引 pandas 数据框的第二级,以便第二级成为一个(完整)列表0,...,(N-1)
对于每个一级索引。
- 我尝试使用艾伦/海登的方法 https://stackoverflow.com/questions/20104874/reindex-sublevel-of-pandas-dataframe-multiindex,但不幸的是它只创建一个包含与先前存在的行数一样多的索引。
- 我想要的是对于每个新索引,都会插入新行(具有 nan 值)。
Example:
df = pd.DataFrame({
'first': ['one', 'one', 'one', 'two', 'two', 'three'],
'second': [0, 1, 2, 0, 1, 1],
'value': [1, 2, 3, 4, 5, 6]
})
print df
first second value
0 one 0 1
1 one 1 2
2 one 2 3
3 two 0 4
4 two 1 5
5 three 1 6
# Tried using Allan/Hayden's approach, but no good for this, doesn't add the missing rows
df['second'] = df.reset_index().groupby(['first']).cumcount()
print df
first second value
0 one 0 1
1 one 1 2
2 one 2 3
3 two 0 4
4 two 1 5
5 three 0 6
我想要的结果是:
first second value
0 one 0 1
1 one 1 2
2 one 2 3
3 two 0 4
4 two 1 5
4 two 2 nan <-- INSERTED
5 three 0 6
5 three 1 nan <-- INSERTED
5 three 2 nan <-- INSERTED