Home > Back-end >  Dividing two columns in a dataframe based on condition
Dividing two columns in a dataframe based on condition

Time:10-12

I have the below dataframe:

|module     | name  |value |
|-----------|-------|------|
|node[11]   | x     |4.0   |
|node[11]   | y     |1.0   |
|node[2]    | x     |2.0   |
|node[2]    | y     |3.0   |
|node[21]   | x     |6.0   |
|node[21]   | y     |6.0   |

and would like to create a new dataframe that contains the value (x/y) for each module. so the expected output would be

|module     | out   |
|-----------|-------|
|node[11]   | 4.0   |
|node[2]    | 0.66  |
|node[21]   | 1.0   |

CodePudding user response:

You can just do pivot then calculated what your need

out = df.pivot(*df).eval('x/y').to_frame('out').reset_index()
Out[23]: 
     module       out
0  node[11]  4.000000
1  node[21]  1.000000
2   node[2]  0.666667
  • Related