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

2024-04-27 04:42:40 发布

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

假设我们有一个如下表:

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

有没有一种方法可以在熊猫(或Numpy)身上有效地实现这一点?数据帧可能包含数百万行,我希望此操作最多需要几秒钟。你知道吗

如果没有快速的Pandas/Numpy解决方案,我就用Numba编写代码。然而,由于某些原因,我过去对类似问题的Numba解决方案(nopython&nested for&break)相当慢,这就是为什么我要求更好的方法。你知道吗

上下文:Here我问如何在延迟过期之前从下一行获取时间序列数据帧中每一行的值。这个问题是相关的,但不使用time/a排序列,因此searchsorted不能使用。你知道吗


Tags: 数据方法ltnumpyhere序列解决方案next
2条回答

您只需执行以下几个步骤:

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

您只需要在小于或等于2reindexbfillshiftB上切片df

df['C'] = df.loc[df.B.le(2), 'A'].reindex(df.index).bfill().shift(-1)

Out[599]:
   A    B    C
0  1  1.0  2.0
1  2  2.0  3.0
2  3  2.0  5.0
3  4  3.0  5.0
4  5  2.0  6.0
5  6  1.0  7.0
6  7  1.0  NaN

相关问题 更多 >