19

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

TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114

2 Answers2

28

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
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
6

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'])
piRSquared
  • 285,575
  • 57
  • 475
  • 624