This question already has answers here:
Python pandas insert list into a cell

(6个答案)


4年前关闭。





我想将一个单元格值设置为一个列表。例如说:

df.loc['a']['b'] = ['one', 'two', 'three']


但是,由于出现以下错误,我无法这样做:

ValueError: Must have equal len keys and value when setting with an iterable


我的数据框目前全为零,为nxn。有什么方法可以设置单元格的值,以便在执行df.loc['a']['b']时返回['one', 'two', 'three']

最佳答案

问题是您可能有一个数据框,其中所有列都是类型为float或int的系列。解决方案是将其类型更改为“对象”。

In [3]: df = pd.DataFrame(np.zeros((4,4)))

In [4]: df
Out[4]:
     0    1    2    3
0  0.0  0.0  0.0  0.0
1  0.0  0.0  0.0  0.0
2  0.0  0.0  0.0  0.0
3  0.0  0.0  0.0  0.0

In [5]: df.dtypes
Out[5]:
0    float64
1    float64
2    float64
3    float64
dtype: object

In [6]: df = df.astype('object')

In [7]: df[1][2] = [1,2,3]

In [8]: df
Out[8]:
   0          1  2  3
0  0          0  0  0
1  0          0  0  0
2  0  [1, 2, 3]  0  0
3  0          0  0  0

关于python - Pandas :如何在数据框中存储列表? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38133961/

10-11 19:37
查看更多