[英]Select row in DataFrame based on values in multiple rows
I've got a DataFrame and I'd like to select rows where in one column they have a certain value, AND the row above has a certain value in another column. 我有一个DataFrame,我想选择一行在某一列中具有特定值的行,而上面的行在另一列中具有特定值。 How do I do this without a for loop?
在没有for循环的情况下该如何做?
For example: 例如:
df = pd.DataFrame({'one': [1,2,3,4,1,2,3,4], 'two': [1,2,3,4,5,6,7,8]})
Where I'd like to find the row where df.one
on that row equals 1
, and df.two
on the row above equals 4
, so in the example row number 4 with values [1,5]
. 其中我想找到其中行
df.one
在该行上等于1
,和df.two
对行的上方等于4
,因此,在例如行号4值[1,5]
You can try shift
with boolean indexing
: 您可以尝试使用
boolean indexing
shift
:
print df
one two
0 1 1
1 2 2
2 3 3
3 4 4
4 1 5
5 2 6
6 3 7
7 4 8
print (df.one == 1) & (df.two.shift() == 4)
0 False
1 False
2 False
3 False
4 True
5 False
6 False
7 False
dtype: bool
print df[(df.one == 1) & (df.two.shift() == 4)]
one two
4 1 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.