gpt4 book ai didi

python - 总结当前行与上一行的差异

转载 作者:行者123 更新时间:2023-12-01 08:19:26 24 4
gpt4 key购买 nike

计算当前行与前一行的差异,我有一个简单的数据集和代码如下:

import pandas as pd

data = {'Month' : [1,2,3,4,5,6,7,8,9,10,11,12],
'Rainfall': [112,118,132,129,121,135,148,148,136,119,104,118]}

df = pd.DataFrame(data)

Rainfall = df["Rainfall"]

df['Changes'] = Rainfall.shift(-1) - Rainfall

df['Changes'] = df['Changes'].shift(1)

它显示了更改(如图左部分)。然而我只关心变化是正、负还是零(就像图片的右侧部分)

enter image description here

我尝试添加 IF 条件,但出现错误:

if df['Changes'] > 0:
df['Changes'] = df['Changes'].shift(1)

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

实现这一目标的正确方法是什么?谢谢。

最佳答案

使用numpy.signmap按字典:

d = {1:'Positive', -1:'Negative',0:'Zero'}
df['Changes'] = np.sign(df['Changes'].shift(1)).map(d).fillna('')

print (df)
Month Rainfall Changes
0 1 112
1 2 118 Positive
2 3 132 Positive
3 4 129 Negative
4 5 121 Negative
5 6 135 Positive
6 7 148 Positive
7 8 148 Zero
8 9 136 Negative
9 10 119 Negative
10 11 104 Negative
11 12 118 Positive

另一个解决方案 numpy.select :

s = df['Changes'].shift(1)
df['Changes'] = np.select([s < 0, s > 0, s == 0],
['Negative','Positive','Zero'],
default='')

编辑:

df['Changes'] = df['Changes'].shift(1)
bins = np.arange(-100, 100, step=5)
labels = ['{}-{}'.format(i, j) for i, j in zip(bins[:-1], bins[1:])]

df['Changes'] = pd.cut(df['Changes'], bins=bins, labels=labels)
print (df)
Month Rainfall Changes
0 1 112 NaN
1 2 118 0-5
2 3 132 0-5
3 4 129 -5-0
4 5 121 -5-0
5 6 135 0-5
6 7 148 0-5
7 8 148 -5-0
8 9 136 -5-0
9 10 119 -5-0
10 11 104 -5-0
11 12 118 0-5

关于python - 总结当前行与上一行的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54760821/

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