[英]Pandas: assign a list to all rows of a multi-index dataframe
我有一个多索引 dataframe,比方说
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 中使用list
s 不是一个好主意,但有可能:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.