pandas 如何在多索引 Dataframe 中追加列表

ecbunoof  于 2023-04-18  发布在  其他
关注(0)|答案(2)|浏览(133)

如何将列表追加到多索引 Dataframe 中的特定行?

index = [("s", "1"),("s", "2"),("s", "3"),("s", "4"),("s", "5"), ("c", "1"),("c", "2"),("c", "3"),("c", "4"),("c", "5")]
multi_index = pd.MultiIndex.from_tuples(index)
df = pd.DataFrame({"I1":[11,12,13,14,15,10,22,33,44,55],"I2":[0,1,2,3,4,5,1,1,1,1]}, index=multi_index)
df

此代码的结果

I1  I2
s   1   11  0
    2   12  1
    3   13  2
    4   14  3
    5   15  4
c   1   10  1
    2   22  1
    3   33  1
    4   44  1
    5   55  1

我想在df.loc[“s”].loc ['In1']中追加列表x = [16,17,18,19]
得到

I1  I2
s   1   11  0
    2   12  1
    3   13  2
    4   14  3
    5   15  4
    6   16  NaN
    7   17  NaN
    8   18  NaN
    9   19  NaN
c   1   10  1
    2   22  1
    3   33  1
    4   44  1
    5   55  1

我怎么能做到这一点?

f2uvfpb9

f2uvfpb91#

使用concat的一个选项:

x = [16,17,18,19]

last_max = int(df.loc['s'].index.max())

tmp = pd.DataFrame({'I1': x})
tmp.index = (tmp.index+last_max).astype(str)

out = (pd.concat([df, pd.concat([tmp], keys='s')])
         .sort_index(level=0, sort_remaining=False, kind='stable')
      )

输出:

I1   I2
c 1  10  5.0
  2  22  1.0
  3  33  1.0
  4  44  1.0
  5  55  1.0
s 1  11  0.0
  2  12  1.0
  3  13  2.0
  4  14  3.0
  5  15  4.0
  5  16  NaN
  6  17  NaN
  7  18  NaN
  8  19  NaN

@cs95建议的替代方案:

pd.concat([df,
           pd.DataFrame(x, columns=['I1'],
                        index=pd.MultiIndex.from_product([['s'],np.arange(1,len(x)+1)
                                                          + int(df.loc['s'].index[-1])
                                                         ]))
          ]).sort_index()
zzlelutf

zzlelutf2#

可以使用reindex为索引的新值插入新索引,然后使用loc将新值分配给I1

x = [16, 17, 18, 19]
s_last = int(df.loc["s"].index[-1])
new_idx = pd.MultiIndex.from_product(
    [["s"], map(str, range(s_last + 1, s_last + len(x) + 1))]
)
df = df.reindex(df.index.union(new_idx))
df.loc[new_idx, "I1"] = x

print(df)

       I1   I2
c 1  10.0  5.0
  2  22.0  1.0
  3  33.0  1.0
  4  44.0  1.0
  5  55.0  1.0
s 1  11.0  0.0
  2  12.0  1.0
  3  13.0  2.0
  4  14.0  3.0
  5  15.0  4.0
  6  16.0  NaN
  7  17.0  NaN
  8  18.0  NaN
  9  19.0  NaN

相关问题