Pandas Dataframe-将列值替换为倒数 [英] Pandas Dataframe - Replace column values with reciprocal
本文介绍了Pandas Dataframe-将列值替换为倒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据框如下所示
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?
推荐答案
我认为您需要与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
或使用 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
或使用 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
这篇关于Pandas Dataframe-将列值替换为倒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文