My dataframe looks like follows
0 1 2 3 4
0 0.660377 0.75 0.728395 1.000000 0.011364
1 0.452830 0.50 0.629630 0.083333 0.045455
2 0.971698 0.75 0.975309 0.166667 0.079545
3 0.169811 0.25 0.172840 0.291667 0.068182
4 0.216981 0.25 0.222222 0.000000 0.090909
5 0.669811 0.50 0.839506 0.333333 0.045455
I need to replace first column with its reciprocal values. Is there any built-in way to do that in Pandas?
I think you need divide with 1:
df[0] = 1 / df[0]
print (df)
0 1 2 3 4
0 1.514287 0.75 0.728395 1.000000 0.011364
1 2.208334 0.50 0.629630 0.083333 0.045455
2 1.029126 0.75 0.975309 0.166667 0.079545
3 5.888900 0.25 0.172840 0.291667 0.068182
4 4.608698 0.25 0.222222 0.000000 0.090909
5 1.492958 0.50 0.839506 0.333333 0.045455
Or use DataFrame.rdiv:
df[0] = df[0].rdiv(1)
print (df)
0 1 2 3 4
0 1.514287 0.75 0.728395 1.000000 0.011364
1 2.208334 0.50 0.629630 0.083333 0.045455
2 1.029126 0.75 0.975309 0.166667 0.079545
3 5.888900 0.25 0.172840 0.291667 0.068182
4 4.608698 0.25 0.222222 0.000000 0.090909
5 1.492958 0.50 0.839506 0.333333 0.045455
Or use numpy.reciprocal:
df[0] = np.reciprocal(df[0])
print (df)
0 1 2 3 4
0 1.514287 0.75 0.728395 1.000000 0.011364
1 2.208334 0.50 0.629630 0.083333 0.045455
2 1.029126 0.75 0.975309 0.166667 0.079545
3 5.888900 0.25 0.172840 0.291667 0.068182
4 4.608698 0.25 0.222222 0.000000 0.090909
5 1.492958 0.50 0.839506 0.333333 0.045455
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With