Pandas:将一个列表分配给多索引数据框架的所有行。

问题描述 投票:0回答:1

我有一个多索引的数据框架,比如说

index = [['a', 'a', 'b', 'b'],[1, 2, 1, 2]]
df = pd.DataFrame([1,2,3,4], index=index)

     0
a 1  1
  2  2
b 1  3
  2  4

如果我想添加一个新的具有常量值的列,我只需做以下操作

df['new_col'] = 'IamNew'

     0 new_col
a 1  1  IamNew
  2  2  IamNew
b 1  3  IamNew
  2  4  IamNew

很完美。但是,如果我想用列表添加一个新的列呢?这是不可能的

df['new_col']=[1,2]
ValueError: Length of values does not match length of index

我试过很多方案,花了不少时间想弄明白这个问题。有什么办法吗?

pandas multi-index
1个回答
1
投票

首先我认为用 list在大熊猫中是不 好主意但有可能。

df['new_col']=pd.Series([[1,2]] * len(df), index=df.index)
print (df)
     0 new_col
a 1  1  [1, 2]
  2  2  [1, 2]
b 1  3  [1, 2]
  2  4  [1, 2]

另一种解决方案。

df['new_col']= [[1,2]] * len(df)
© www.soinside.com 2019 - 2024. All rights reserved.