微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Pandas 中,如何更新迭代器中的上一行?

如何解决在 Pandas 中,如何更新迭代器中的上一行?

我正在尝试迭代一个数据框并在每次迭代时更新前一行。我的索引是基于日期的。

for i,row in df.iterrows():
    # do my calculations here
    myValue = row['myCol']
    prev = row.shift()
    prev['myCol'] = prev['myCol'] - myValue

没有错误但没有保存,我该如何保存?

解决方法

如果没有示例数据,就不清楚您在尝试什么。但是使用您的 for 循环中的操作,它可以可能像这样完成,而不需要任何循环:

myValue = df['myCol']  # the column you wanted and other calculations
df['myCol'] = df['myCol'].shift() - myValue

根据您的尝试,其中之一应该是您想要的:

# starting with this df
   myCol  otherCol
0      2         6
1      9         3
2      4         8
3      2         8
4      1         7

# next row minus current row
df['myCol'] = df['myCol'].shift(-1) - df['myCol']
df
# result:
   myCol  otherCol
0    7.0         6
1   -5.0         3
2   -2.0         8
3   -1.0         8
4    NaN         7

# previous row minus current row
df['myCol'] = df['myCol'].shift() - df['myCol']
df
# result:
   myCol  otherCol
0    NaN         6
1   -7.0         3
2    5.0         8
3    2.0         8
4    1.0         7

myVal 可以是任何东西,比如对整个列进行矢量化的一些数学运算:

myVal = df['myCol'] * 2 + 3
# myVal is:
0     7
1    21
2    11
3     7
4     5
Name: myCol,dtype: int32

df['myCol'] = df['myCol'].shift(-1) - myVal
df
   myCol  otherCol
0    2.0         6
1  -17.0         3
2   -9.0         8
3   -6.0         8
4    NaN         7

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。