pandas :如何在数据框中存储列表? [英] pandas: how to store a list in a dataframe?

查看:148
本文介绍了 pandas :如何在数据框中存储列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to set a cell value as a list. Say for example:

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

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

However, I'm unable to do so as I get the following error:

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

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

My dataframe currently is just all zeros and is nxn. Is there any way to be able to set the cell value so that when I execute df.loc['a']['b'], I get back ['one', 'two', 'three'].

推荐答案

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

The problem is that you likely have a dataframe where all the columns are series of type float or int. The solution is to change them type '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

这篇关于 pandas :如何在数据框中存储列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆