Divide One Pandas Dataframe by Another - ignore index but respect columns

I have 2 data frames. I would like to broadcast the split operation

df1= pd.DataFrame([[1.,2.,3.,4.], [5.,6.,7.,8.], [9.,10.,11.,12.]], columns=['A','B','C','D'], index=['x','y','z']) df2= pd.DataFrame([[0.,1.,2.,3.]], columns=['A','B','D','C'], index=['q']) 

Note that the columns are aligned slightly differently in df2.

I would like to divide df1 by df2 where the row is passed, but the column labels are followed.

  ABCD x 1 2 3 4 y 5 6 7 8 z 9 10 11 12 ABDC q 0 1 2 3 

That would be wrong.

 df1.values/df2.values [[ inf 2. 1.5 1.33333333] [ inf 6. 3.5 2.66666667] [ inf 10. 5.5 4. ]] 

Answer: I wish:

  ABCD x inf 2 1 2 y inf 6 2.33 4 z inf 10 3.66 6 
+5
source share
3 answers

If you divide by a series (by selecting one row of the second data block), pandas will align this series with the columns of the first data frame, providing the desired result:

 In [75]: df1 / df2.loc['q'] Out[75]: ABCD x inf 2 1.000000 2 y inf 6 2.333333 4 z inf 10 3.666667 6 

If you don't know / don't want to use the name of this single row, you can use squeeze to convert a single-column dataframe to a row: df1 / df2.squeeze() (see @EdChum answer).

+2
source

Perhaps you could order the df2 columns the same from df1 , and then separate the values

 In [53]: df1.values/df2[df1.columns].values Out[53]: array([[ inf, 2. , 1. , 2. ], [ inf, 6. , 2.33333333, 4. ], [ inf, 10. , 3.66666667, 6. ]]) 
+1
source

You can rearrange the column and then call squeeze to smooth the array and then call the div :

 In [114]: df1= pd.DataFrame( [[1.,2.,3.,4.],[5.,6.,7.,8.],[9.,10.,11.,12.]] ,columns = ['A','B','C','D'], index = ['x','y','z']) df2= pd.DataFrame( [[0.,1.,2.,3.]] ,columns = ['A','B','D','C'], index = ['q']) ​df1.div(df2.ix[:,df1.columns].squeeze()) Out[114]: ABCD x inf 2 1.000000 2 y inf 6 2.333333 4 z inf 10 3.666667 6 

df1/df2.ix[:,df1.columns].squeeze() also works, but @Joris answer is much nicer

EDIT

As @joris pointed out, reordering columns is not necessary, since pandas will naturally align the columns like this:

 df1.div(df2squeeze()) 

or

 df1./df2squeeze() 

will work

+1
source

All Articles