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?

1
  • You shouldn't be using ix, it's deprecated, use either iloc or loc Commented Jul 16, 2018 at 3:09

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

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 ]"
@LiamdeBoeuf look at ast

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.