Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a DataFrame inside a DataFrame

Tags:

python

pandas

I have a DataFrame with various text and numeric columns which I use like a database. Since a column can be of dtype object, I can also store more complex objects inside a single cell, like a numpy array.

How could I store another DataFrame inside a cell?

df1=pd.DataFrame([1,'a'])
df2=pd.DataFrame([2,'b'])

This assigment fails:

df1.loc[0,0] = df2

ValueError: Incompatible indexer with DataFrame

PS. It is not a duplicate question as suggested below since I do not want to concatenate the "sub"-DataFrames

like image 320
adr Avatar asked Oct 28 '25 19:10

adr


2 Answers

You can use set_value:

df1.set_value(0,0,df2)

or:

df1.iat[0,0]=df2

Since .set_value has been deprecated since version 0.21.0.

like image 184
Allen Avatar answered Oct 30 '25 08:10

Allen


Convert your df1 to a dict by using to_dict

df1.loc[0,0] = [df2.to_dict()]
df1
Out[862]:
                       0
0  [{0: {0: 2, 1: 'b'}}]
1                      a

If you need convert it back to dataframe , You can using dataframe constructor

pd.DataFrame(df1.loc[0,0][0])


Out[864]: 
   0
0  2
1  b
like image 35
BENY Avatar answered Oct 30 '25 10:10

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!