Pandas:如何在数据框中存储列表?

2024-04-26 10:03:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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']


Tags: anddf列表lenvaluehave错误equal
2条回答

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

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

问题是,您可能有一个dataframe,其中所有列都是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

相关问题 更多 >