首页 > 解决方案 > Output next row from criteria in Python DataFrame

问题描述

I am trying to find a way to get the next row in a Python DataFrame when the rows in another column is equal to something. In the below example I am looking to get the next row in column A when rows in column B says negative. The end result should be C in the last DataFrame. The output should be in another DataFrame format. How do I do that?

Test={'A':[1.5,2.3,3.5,4.4, 5.6, 7.8, 8.9], 'B':['Neg', 'Pos', 'Neg', 'Pos', 'Pos', 'Neg','Pos']}
Dataframe=pd.DataFrame(Test)
Dataframe
Test={'A':[1.5,2.3,3.5,4.4, 5.6, 7.8, 8.9], 'B':['Neg', 'Pos', 'Neg', 'Pos', 'Pos', 'Neg','Pos']}
Dataframe=pd.DataFrame(Test)
Dataframe
       A    B
   0    1.5 Neg
   1    2.3 Pos
   2    3.5 Neg
   3    4.4 Pos
   4    5.6 Pos
   5    7.8 Neg
   6    8.9 Pos



         C
   0    2.3
   1    4.4
   2    8.9

标签: pythondataframerownext

解决方案


pandas.Series.shift与 一起使用reset_index

df["A"].shift(-1)[df["B"].eq("Neg")].reset_index(drop=True)

输出:

0    2.3
1    4.4
2    8.9
Name: A, dtype: float64

推荐阅读