解决方案如果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'? –