解決方案如果list1
length
是一樣的DataFrame
長度:
您需要創建Series
先用相同的索引df
,然後分配到新列:
print (pd.Series(list1, index=df.index))
0 {'b': 2, 'a': 1}
2 {'d': 2, 'c': 1}
dtype: object
df['D'] = pd.Series(list1, index=df.index)
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
與DataFrame.assign
另一種解決方案:
df = df.assign(D=pd.Series(list1, index=df.index))
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
S olution對此事發表評論,謝謝Nickil Maveli:
df.loc[:, 'D'] = list1
或者更好:
df['D'] = list1
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
如果lenghts是不同的,它是一個比較複雜 - 通過df.index
length
的位置需要選擇並通過list1
length
:
print (df)
A B C D
0 a b c NaN
2 x y z NaN
5 y e t NaN
list1 = [{'a':1,'b':2},{'c':1,'d':2}]
df['D'] = pd.Series(list1[:len(df.index)], index=df.index[:len(list1)])
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
5 y e t NaN
print (df)
A B C D
0 a b c NaN
2 x y z NaN
5 y e t NaN
list1 = [{'a':1,'b':2},{'c':1,'d':2}, {'a':1,'b':2},{'c':1,'d':2}]
df['D'] = pd.Series(list1[:len(df.index)], index=df.index[:len(list1)])
print (df)
A B C D
0 a b c {'b': 2, 'a': 1}
2 x y z {'d': 2, 'c': 1}
5 y e t {'b': 2, 'a': 1}
這裏是不是一個簡單的'loc'就足夠了 - 'df.loc [:,'D'] = L'? –