所以我有一个 df,我想根据子集为特定列分配一个列表。所以让我们说这是我的 df:
d = {'foo':[100, 111, 222],
'bar':[333, 444, 555]}
df = pd.DataFrame(d)
>>df
bar foo
0 333 100
1 444 111
2 555 222
我现在想分配[1,2,3,4]
给列的第一行和第三行foo
,以获得这个 df:
bar foo
0 333 [1,2,3,4]
1 444 111
2 555 [1,2,3,4]
我希望是这样的:
df.loc[[0,2],'foo'] = [1,2,3,4]
工作,但它会产生以下错误:
ValueError: shape mismatch: value array of shape (4,) could not be broadcast to indexing result of shape (2,)
使用at
:
df.at[[0,2],'foo'] = [1,2,3,4]
抛出同样的错误。
有任何想法吗?
谢谢!
尝试:
indx = [0,2]
df.loc[indx, 'foo'] = pd.Series([[1,2,3,4]] * len(indx), index=indx)
df
@MadPhysicist 评论了一个更好的解决方案
df.loc[indx, 'foo'] = pd.Series([[1,2,3,4] for _ in range(len(indx))], index = indx)
输出:
foo bar
0 [1, 2, 3, 4] 333
1 111 444
2 [1, 2, 3, 4] 555
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句