Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating interaction terms from two dataframes

Tags:

python

pandas

I have two aligned dataframes of dummies variables. I would like to multiply the two and obtain a new dataframe result of an interaction of the two with 3 rows and 6 columns (ItalyxJan, ItalyxFeb, ItalyxMar, ChinaxJan..)

# Creating the first dataframe  
df1=pd.DataFrame({"Italy":[0,0,1], 
                  "China":[1,1,0]}) 

# Creating the second dataframe with <code>Na</code> value 
df2=pd.DataFrame({"Jan":[1,0,0], 
                  "Feb":[0,1,0], 
                  "Mar":[0,0,1]}) 

df3 = df1.mul(df2.values, axis=0)

, but I received an error

ValueError: Unable to coerce to DataFrame, shape must be (3, 2): given (3, 3)


##Expected outputs

df3=pd.DataFrame({"Italy*Jan":[0,0,0], 
                  "Italy*Feb":[0,0,0], 
                  "Italy*Mar":[0,0,1],
                  "China*Jan":[1,0,1],
                  "China*fe":[0,1,0],
                  "Chian*Mar":[0,0,0]}) 

Suggestions?

like image 739
Filippo Sebastio Avatar asked Jun 08 '26 06:06

Filippo Sebastio


1 Answers

You can create MultiIndex.from_product and DataFrame.reindex both, so possible multiple:

mux = pd.MultiIndex.from_product([df1.columns, df2.columns])

df1 = df1.reindex(mux, axis=1, level=0)
print (df1)
  Italy         China        
    Jan Feb Mar   Jan Feb Mar
0     0   0   0     1   1   1
1     0   0   0     1   1   1
2     1   1   1     0   0   0

df2 = df2.reindex(mux, axis=1, level=1)
print (df2)
  Italy         China        
    Jan Feb Mar   Jan Feb Mar
0     1   0   0     1   0   0
1     0   1   0     0   1   0
2     0   1   1     0   1   1

df3 = df1.mul(df2, axis=0)
print (df3)
  Italy         China        
    Jan Feb Mar   Jan Feb Mar
0     0   0   0     1   0   0
1     0   0   0     0   1   0
2     0   1   1     0   0   0

Last is possible flatten MultiIndex with map and join:

df3.columns = df3.columns.map('x'.join)
print (df3)
   ItalyxJan  ItalyxFeb  ItalyxMar  ChinaxJan  ChinaxFeb  ChinaxMar
0          0          0          0          1          0          0
1          0          0          0          0          1          0
2          0          1          1          0          0          0
like image 158
jezrael Avatar answered Jun 10 '26 17:06

jezrael