gpt4 book ai didi

python - 如何在数据框中将第二列除以第一列?

转载 作者:行者123 更新时间:2023-12-04 07:51:39 25 4
gpt4 key购买 nike

     DP 1       DP 2        DP 3       DP 4        DP 5         DP 6        DP 7        DP 8       DP 9        DP 10
3,57,848 11,24,788 17,35,330 22,18,270 27,45,596 33,19,994 34,66,336 36,06,286 38,33,515 39,01,463
3,52,118 12,36,139 21,70,033 33,53,322 37,99,067 41,20,063 46,47,867 49,14,039 53,39,085
2,90,507 12,92,306 22,18,525 32,35,179 39,85,995 41,32,918 46,28,910 49,09,315
3,10,608 14,18,858 21,95,047 37,57,447 40,29,929 43,81,982 45,88,268
4,43,160 11,36,350 21,28,333 28,97,821 34,02,672 38,73,311
3,96,132 13,33,217 21,80,715 29,85,752 36,91,712
4,40,832 12,88,463 24,19,861 34,83,130
3,59,480 14,21,128 28,64,498
3,76,686 13,63,294
3,44,014
我有这个三角形数据框(df1),我想计算包含结果的新数据框(df2):second_column(df2)/first_column(df2) 和third_column(df2)/second_column(df2) 等等..
我试过这样(我知道这是错误的)。
for colname, col in df1.iteritems():
df1[colname7] = df1['second_column']/df1['first_column']
我想要这样的 df2:
  DP 1   DP 2    DP 3    DP 4    DP 5    DP 6    DP 7    DP 8    DP 9   DP 10
3.14 1.54 1.28 1.24 1.21 1.04 1.04 1.06 1.02 -
3.51 1.76 1.55 1.13 1.08 1.13 1.06 1.09 -
4.45 1.72 1.46 1.23 1.04 1.12 1.06 -
4.57 1.55 1.71 1.07 1.09 1.05 -
2.56 1.87 1.36 1.17 1.14 -
3.37 1.64 1.37 1.24 -
2.92 1.88 1.44 -
3.95 2.02 -
3.62 -


感谢您的时间..

最佳答案

首先,您需要删除逗号并将数据框转换为浮点类型:

df2 = df1.replace(',', '', regex = True).astype(float)
然后你可以通过一次移动列来直接划分:
df2 = df2.shift(-1, axis = 1).div(df2)
输出
df2
DP 1 DP 2 DP 3 DP 4 DP 5 DP 6 DP 7 DP 8 DP 9 DP 10
0 3.143200 1.542806 1.278299 1.237719 1.209207 1.044079 1.040374 1.063009 1.017725 NaN
1 3.510582 1.755493 1.545286 1.132926 1.084493 1.128106 1.057268 1.086496 NaN NaN
2 4.448450 1.716718 1.458257 1.232079 1.036860 1.120010 1.060577 NaN NaN NaN
3 4.568002 1.547052 1.711784 1.072518 1.087360 1.047076 NaN NaN NaN NaN
4 2.564198 1.872956 1.361545 1.174217 1.138315 NaN NaN NaN NaN NaN
5 3.365588 1.635679 1.369162 1.236443 NaN NaN NaN NaN NaN NaN
6 2.922798 1.878099 1.439393 NaN NaN NaN NaN NaN NaN NaN
7 3.953288 2.015651 NaN NaN NaN NaN NaN NaN NaN NaN
8 3.619179 NaN NaN NaN NaN NaN NaN NaN NaN NaN
9 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN


(可选)您可以舍入:
df2 = df2.round(2)

关于python - 如何在数据框中将第二列除以第一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66939075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com