我有一个多索引数据帧,我想向每个最外层索引添加另一行,其中其他两个索引用特定字符串标记(所有值中的所有索引都使用相同的字符串)。该行的其他值可以为空或其他任何值。
我尝试使用 groupby 创建不同的数据框并附加它们,但我无法让索引工作。
例如,对于数据框:
Index1 Index2 Index3 val
A d 1 a
A d 2 b
A e 3 c
A e 4 d
B f 5 e
B f 6 f
B g 7 g
C h 8 h
C h 9 i
C i 10 j
我想得到:
Index1 Index2 Index3 val
A d 1 a
A d 2 b
A e 3 c
A e 4 d
A StringA StringA <any value>
B f 5 e
B f 6 f
B g 7 g
B StringA StringA <any value>
C h 8 h
C h 9 i
C i 10 j
C StringA StringA <any value>
最佳答案
IIUC
s=pd.DataFrame({'Index1':df.Index1.unique(),
'Index2':df.Index1.radd('String').unique(),
'Index3': df.Index1.radd('String').unique(),
'val':[1]*df.Index1.nunique()})
pd.concat([df.reset_index(),s]).sort_values('Index1').set_index(['Index1','Index2','Index3'])
Out[301]:
Index1 Index2 Index3 val
0 A d 1 a
1 A d 2 b
2 A e 3 c
3 A e 4 d
0 A StringA StringA 1
4 B f 5 e
5 B f 6 f
6 B g 7 g
1 B StringB StringB 1
7 C h 8 h
8 C h 9 i
9 C i 10 j
2 C StringC StringC 1
关于python - 向多索引数据帧上的每个索引添加一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58617898/