4

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

3
  • Does the failing statement work with just = 1 Commented Jan 21, 2018 at 22:43
  • Possible duplicate of DataFrame of DataFrames with pandas Commented Jan 21, 2018 at 22:46
  • What is the purpose of nesting a dataframe within one? This sounds like an XY Problem. Consider a dictionary or list of dataframes. Commented Jan 22, 2018 at 2:55

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

...or df1.at[0,0]=df2 for labels... Thanks!
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.