我想使用尽可能少的循环来检查数据框中6列之间的最高增量。

2024-04-30 07:00:09 发布

您现在位置:Python中文网/ 问答频道 /正文

POPESTIMATES是2010-2015年的实际pop估计值,我想得到年份之间的最大差值。所以我必须检查| POPESTIMATE2015-POPESTIMATE2014 |,| POPESTIMATE2015-POPESTIMATE2014 |…| POPESTIMATE2013-POPESTIMATE2010 |。。。然后找到最高的绝对值。 这是我写的方法,但我收到了一个无法将浮点Nan转换为整数的错误,它太慢了。我相信有一个更有效的方法来做到这一点。有什么想法吗

def question7():
c = census_df
c['delta'] = 0
c['delta_max'] = 0
x = 5
y = 0
for index, row in c.iterrows():
    while x > 0:
        while y > -1:
            c.loc[index, ['delta']] = (c.loc[index, ['POPESTIMATE201' + str(x)]] - c.loc[index, ['POPESTIMATE201' + str(y)]]).abs()
            if int(c.loc[index, ['delta']]) > int(c.loc[index, ['delta_max']]):
                c.loc[index, ['delta_max']] = c.loc[index, ['delta']]
            y -= 1
        x -= 1
return c['delta_max']

Tags: 方法index估计值poplocmaxintdelta
1条回答
网友
1楼 · 发布于 2024-04-30 07:00:09

我认为需要^{}

df = pd.DataFrame(np.random.randint(15, size=(5, 6)))
df[[1, 4]] *= -1
df.columns = ['POP{}'.format(i) for i in range(2010, 2016)]
df['delta_max'] = np.ptp(df.values, axis=1)
print(df)
   POP2010  POP2011  POP2012  POP2013  POP2014  POP2015  delta_max
0        8      -12        0        4       -1        2         20
1        5      -10        4        1       -4        1         15
2        1       -8        1       10      -10        5         20
3        0       -7        4        8      -13        4         21
4        1       -3        8        0      -12        2         20

相关问题 更多 >