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

Ala*_*anH 8 python dataframe pandas

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

df.loc['a']['b'] = ['one', 'two', 'three']
Run Code Online (Sandbox Code Playgroud)

但是,我无法这样做,因为我收到以下错误:

ValueError: Must have equal len keys and value when setting with an iterable
Run Code Online (Sandbox Code Playgroud)

我的数据框目前只是全零并且是nxn.有没有办法能够设置单元格值,这样当我执行时df.loc['a']['b'],我会回来['one', 'two', 'three'].

jua*_*aga 24

问题是你可能有一个数据框,其中所有列都是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
Run Code Online (Sandbox Code Playgroud)


piR*_*red 6

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

df.loc[['a'], ['b']] = df.loc[['a'], ['b']].applymap(lambda x: ['one', 'two', 'three'])
Run Code Online (Sandbox Code Playgroud)