[英]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.