Python 熊猫:如何在数据框中存储列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38133961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas: how to store a list in a dataframe?
提问by AlanH
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
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']
.
我的数据框目前只是全零并且是 nxn。有什么办法可以设置单元格值,以便在我执行时df.loc['a']['b']
返回['one', 'two', 'three']
。
回答by juanpa.arrivillaga
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.'
问题是您可能有一个数据框,其中所有列都是 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
回答by piRSquared
This is a tortured way of doing it. I really hope someone has a better answer.
这是一种折磨人的方式。我真的希望有人有更好的答案。
df.loc[['a'], ['b']] = df.loc[['a'], ['b']].applymap(lambda x: ['one', 'two', 'three'])