2

Is it possible to store a numpy array in a single pandas cell? For example, let's assume we have the following df

import pandas as pd
import numpy as np
df= pd.DataFrame(np.nan, columns =["A","B","C"], index =np.arange(5))

It is possible to set a specific cell as follows

df.ix[1,"A"]=2 # This works

However, if I try to assign an numpy array, it fails with a ValueError: setting an array element with a sequence. exception.

df.ix[1,"A"]=np.arange(5) #This fails

Is there any way to solve this? There is a similar solution on SO and it suggests to pass the values as numpy array as list but it seems not to work in my case.

df.ix[1,"A"]=list(np.arange(5)) #This also fails

Any suggestions?

Liam deBoeuf
  • 131
  • 3
  • 9

1 Answers1

7

Set your df to object then using at

df=df.astype(object)
df.at[2, 'A']=np.arange(5).tolist()
df
Out[422]: 
                 A    B    C
0              NaN  NaN  NaN
1              NaN  NaN  NaN
2  [0, 1, 2, 3, 4]  NaN  NaN
3              NaN  NaN  NaN
4              NaN  NaN  NaN
BENY
  • 317,841
  • 20
  • 164
  • 234
  • Thanks for your help. Do you know how to convert the df back to a numeric datatype? the `df.apply(pd.to_numeric)` the approach does not work in my case since the cell is saved as a string of values like this`"[792.6825 792.625 792.44 ... 896.795 897.1425 897.59 ]"` – Liam deBoeuf Jul 16 '18 at 05:10
  • 1
    @LiamdeBoeuf look at `ast` – BENY Jul 16 '18 at 14:19