gpt4 book ai didi

python - 如何为每一行获取下一行中与 Pandas 中的条件匹配的值?

转载 作者:行者123 更新时间:2023-12-01 00:40:28 25 4
gpt4 key购买 nike

假设我们有一个如下所示的表:

A B
1 1.0
2 2.0
3 2.0
4 3.0
5 2.0
6 1.0
7 1.0

现在我想为每一行获取下一行的 A 列的值,其中 B <= 2.0。结果存储在C中。然后我们得到:

A B   C
1 1.0 2
2 2.0 3 # Here we skip a row because next.B > 2.0
3 2.0 5
4 3.0 5
5 2.0 6
6 1.0 7
7 1.0 Na

有没有办法在 Pandas(或 Numpy)中有效地实现这一点?数据框可能包含数百万行,我希望此操作最多需要几秒钟。

如果没有快速的 Pandas/Numpy 解决方案,我将直接使用 Numba 进行编码。然而,由于某种原因,我过去解决类似问题的 Numba 解决方案(nopython & Nested for & Break)相当慢,这就是为什么我要求更好的方法。

上下文:Here我问如何在延迟到期之前为时间序列数据帧中的每一行获取下一行的值。这个问题是相关的,但不使用时间/排序列,因此无法使用searchsorted

最佳答案

您只需执行以下几个步骤即可完成此操作:

import pandas as pd
import numpy as np

# initialize column 'C' with the value of column 'A'
# for all rows with values for 'B' smaller than 2.0
# use np.NaN if 'C' if 'B' > 2.0
# because normal int columns do not support null values
# we use the new type Int64 instead
# (new in pandas version 0.25)
df['C']= df['A'].astype('Int64').where(df['B']<=2.0, np.NaN)

# now just fill the gaps using the value of the next row
# in which the field is filled and shift the column
df['C'].fillna(method='bfill', inplace=True)
df['C']=df['C'].shift(-1)

这会导致:

>>> df
A B C
0 1 1.0 2
1 2 2.0 3
2 3 2.0 5
3 4 3.0 5
4 5 2.0 6
5 6 1.0 7
6 7 1.0 NaN

关于python - 如何为每一行获取下一行中与 Pandas 中的条件匹配的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57381533/

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