简体   繁体   English

在熊猫中迭代构建多索引数据框

[英]Iteratively build multi-index dataframe in pandas

I have n small dataframes which I combine into one multiindex dataframe. 我有n小型数据框,它们组合成一个多索引数据框。

d1 = DataFrame(np.array([
    ['a', 5, 9],
    ['b', 4, 61],
    ['c', 24, 9]]),
    columns=['name', 'attr11', 'attr22'])

d2 = DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22'])

d3 = DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['d', 10, 14],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22'])

How to combine these into one dataframe? 如何将它们组合成一个数据帧?

Result: 结果:

      name attr11 attr21  attr22
d1    a    5    NULL    9
      b    4    NULL    61
      c    24   NULL    9
d2    a    NULL   5    19
      b    NULL   14   16
      c    NULL   4    9
d3    a    NULL   5    19 
      b    NULL   14   16
      c    NULL   4    9
      d    NULL   10   14

you can build the multiindex after the concatenation. 您可以在连接后构建多multiindex You just need to add a column to each frame with the dataframe id: 您只需要在每个具有数据框ID的框架中添加一列:

frames =[d1,d2,d3]

Add a column to each frame with the frame id: 在每个具有框架ID的框架中添加一列:

for x in enumerate(frames):
    x[1]['frame_id'] = 'd'+str(x[0]+1)

then concatenate the list of frames and set the index on the desired columns: 然后连接框架列表,并在所需的列上设置索引:

pd.concat(frames).set_index(['frame_id','name'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM