gpt4 book ai didi

python-3.x - 在有条件的 Pandas 中除以前一行

转载 作者:行者123 更新时间:2023-12-04 10:24:40 24 4
gpt4 key购买 nike

我正在尝试创建一个新列,它是前一行的划分。但是某些行的值为 0。所以我的条件语句是:如果2行之间的除法是无穷大或nan,则Growth rate列中的值将为0。否则,它将与前一行相除。

'''
n=len(df)
对于范围内的 j (0,n-1):

if ((df.iloc[j,4]/df.iloc[j-1,4]) == inf):
df['GrowthRate']=0
else:
df['GrowthRate'] = df.iloc[j,4]/df.iloc[j-1,4]
j=j+1

'''

输出是我在列中的所有值都是 inf。

最佳答案

使用 replace 的另一种解决方案和 fillna 处理NaNInf :

import numpy as np

df['GrowthRate'] = (df.iloc[:, 4].div(df.iloc[:, 4].shift())
.fillna(0).replace([np.inf, -np.inf], 0))

示例
np.random.seed(2020)
df = pd.DataFrame(np.random.randint(-3, 4, (10, 5)))
print(df)

# 0 1 2 3 4
# 0 -3 -3 0 3 0
# 1 0 2 0 -3 2
# 2 -3 -3 -3 -1 -2
# 3 0 0 -1 3 0
# 4 3 2 -3 1 1
# 5 -3 3 1 -2 -2
# 6 2 -1 -2 3 2
# 7 2 -1 3 3 3
# 8 2 1 3 3 1
# 9 -1 0 1 -2 1

df['GrowthRate'] = (df.iloc[:, 4].div(df.iloc[:, 4].shift())
.fillna(0).replace([np.inf, -np.inf], 0))

[出去]
   0  1  2  3  4  GrowthRate
0 -3 -3 0 3 0 0.000000
1 0 2 0 -3 2 0.000000
2 -3 -3 -3 -1 -2 -1.000000
3 0 0 -1 3 0 -0.000000
4 3 2 -3 1 1 0.000000
5 -3 3 1 -2 -2 -2.000000
6 2 -1 -2 3 2 -1.000000
7 2 -1 3 3 3 1.500000
8 2 1 3 3 1 0.333333
9 -1 0 1 -2 1 1.000000

关于python-3.x - 在有条件的 Pandas 中除以前一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60672661/

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