Suman Chowdhury
Suman Chowdhury

Reputation: 53

how to use custom calculation based on two dataframes in python

I have 2 dataframes as below,

df1

index   X1  X2  X3  X4
0   6   10  6   7
1   8   9   11  13
2   12  13  15  11
3   8   11  7   6
4   11  7   6   6
5   13  14  11  10

df2

index   Y
0   20
1   14
2   17
3   14
4   15
5   20

I want to get 3rd dataframe such that new X(i) = Y - (Y/X(i))

index   X1  X2  X3  X4
0   16.67   18.00   16.67   17.14
1   12.25   12.44   12.73   12.92
2   15.58   15.69   15.87   15.45
3   12.25   12.73   12.00   11.67
4   13.64   12.86   12.50   12.50
5   18.46   18.57   18.18   18.00

Please note, it shall match the index number of df1 and df2 while calculating. Thanks in advance!

Upvotes: 0

Views: 36

Answers (2)

BENY
BENY

Reputation: 323226

Base on pandas

-(1/df1.div(df2.Y,0)).sub(df2.Y,0)
Out[634]: 
              X1         X2         X3         X4
index                                            
0      16.666667  18.000000  16.666667  17.142857
1      12.250000  12.444444  12.727273  12.923077
2      15.583333  15.692308  15.866667  15.454545
3      12.250000  12.727273  12.000000  11.666667
4      13.636364  12.857143  12.500000  12.500000
5      18.461538  18.571429  18.181818  18.000000

Upvotes: 1

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

You can use numpy for vectorized solution i.e

df[df.columns] = (df2.values - df2.values/df.values)

           X1         X2         X3         X4
index                                            
0      16.666667  18.000000  16.666667  17.142857
1      12.250000  12.444444  12.727273  12.923077
2      15.583333  15.692308  15.866667  15.454545
3      12.250000  12.727273  12.000000  11.666667
4      13.636364  12.857143  12.500000  12.500000
5      18.461538  18.571429  18.181818  18.000000

Upvotes: 1

Related Questions