store pandas dataframe in a dataframe and expand

Viewed 25

I have the two following dataframes:

data1 = [['A', 'one'], ['B', 'two'], ['C', 'three']]
df1 = pd.DataFrame(data1, columns=['column1', 'column2'])

column1 column2
0   A   one
1   B   two
2   C   three

and

data2 = [['aa', 'o'], ['bb', 't']]
df2 = pd.DataFrame(data2, columns=['columnA', 'columnB'])

columnA columnB
0   aa  o
1   bb  t

Then I put df2 into df1 (into the upper right cell):

df1['column2'][0] = df2 

Now I want to expand the resulting dataframe such way that it looks as follows:

column1 column2 column2.columnA column2.columnB
0   A   *       aa              o
1   A   *       bb              t
2   B   two     NaN             NaN
3   C   three   NaN             NaN

* can be whatever value
1 Answers

Maybe introduce a temporary column containing just 'A' to df2 and merge:

df2["tmp"] = "A"
df3 = df1.merge(df2, 
                left_on="column1", 
                right_on=df2.pop("tmp"), 
                how="left")

>>> df3
  column1 column2 columnA columnB
0       A     one      aa       o
1       A     one      bb       t
2       B     two     NaN     NaN
3       C   three     NaN     NaN
Related