Python 熊猫:如何在数据框中存储列表?

Python 熊猫:如何在数据框中存储列表?,python,pandas,dataframe,Python,Pandas,Dataframe,我想将单元格值设置为列表。比如说: 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']时,我会返回['1','2','3']这是一种折磨人的方法。我真的

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

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']
时,我会返回
['1','2','3']

这是一种折磨人的方法。我真的希望有人有更好的答案

df.loc[['a'], ['b']] = df.loc[['a'], ['b']].applymap(lambda x: ['one', 'two', 'three'])

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

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

df.loc['a']['b']=['one'、'two'、'three']]
有效吗?你不能在一列上设置数据类型吗?@juanpa.arrivillaga是的,我只需要做一列,因为Merlin提到了一个很好的解决方案。将其保留在书签中:)