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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With