Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas: how to store a list in a dataframe? [duplicate]

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

like image 203
TheRealFakeNews Avatar asked Jun 30 '16 22:06

TheRealFakeNews


People also ask

Can I store a list in a Pandas DataFrame?

You can insert a list of values into a cell in Pandas DataFrame using DataFrame.at() , DataFrame. iat() , and DataFrame.

How does pandas handle duplicates in DataFrame?

Use DataFrame. drop_duplicates() to Drop Duplicates and Keep Last Row. You want to select all the duplicate rows and their last occurrence, you must pass a keep argument as "last" .


1 Answers

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
like image 130
juanpa.arrivillaga Avatar answered Oct 11 '22 16:10

juanpa.arrivillaga