如何获得所有阶梯行的首次出现

时间:2018-08-03 19:08:36

标签: pandas

我有一个数据框,该数据框由一些整数组成,键为默认值(int)

test = pd.DataFrame({'num':[3,5,6,21,3,5,6,7,3,5])

如何分配一个新列“ num_apart”来找出当前行与值> x的第一行之间的键差?

1 个答案:

答案 0 :(得分:1)

首先使用diff获取每一行之间的阶梯,然后我们使用idxmax查找首次出现的阶梯超出边界

test = pd.DataFrame({'num':[3,5,6,21,3,5,6,7,3,5]})
test['num_apart']=test.num.diff()
test
Out[118]: 
   num  num_apart
0    3        NaN
1    5        2.0
2    6        1.0
3   21       15.0
4    3      -18.0
5    5        2.0
6    6        1.0
7    7        1.0
8    3       -4.0
9    5        2.0

test.num_apart.gt(2).idxmax()# here I am using 2 as the boundary you can change the value to what you need . 
Out[119]: 3