我有一个多索引的数据框架,比如说
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
我试过很多方案,花了不少时间想弄明白这个问题。有什么办法吗?
首先我认为用 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)