python - 向多索引数据帧上的每个索引添加一行

标签 python pandas dataframe

我有一个多索引数据帧,我想向每个最外层索引添加另一行,其中其他两个索引用特定字符串标记(所有值中的所有索引都使用相同的字符串)。该行的其他值可以为空或其他任何值。

我尝试使用 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/

相关文章:

python - 如何使用 BeautifulSoup 获取嵌套在 TD 中的 DIV 内部的链接

python - 对于不规则的分隔符,如何使 pandas read_csv 中的分隔符更加灵活 wrt 空格?

python - 对可能是也可能不是多索引的 pandas 数据帧进行操作

python - 如何使用 pyinstaller 在可执行文件中包含 .dll 文件?

Python:将列表附加到另一个列表并清除第一个列表

Python PyQt4 QSlider 间隔大于 1

python - python 中的 Opencv 2.4.3 estimateRigidTransform

python - 如何获得两个 pandas 系列文本列的交集?

python - 编写 if-else 循环以根据条件填充数据框列时出现 ValueError

python - pandas 数据框中的新列基于带有条件列表的现有列值