简体   繁体   English

根据多行中的值选择DataFrame中的行

[英]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.

相关问题 根据熊猫中MULTIPLE列中的值从DataFrame中选择行 - Select rows from a DataFrame based on values in a MULTIPLE columns in pandas 基于列值的 DataFrame 中的 select 行? - select rows from a DataFrame based on column values? Python DataFrame - 根据另一个数据帧中的值选择数据帧行 - Python DataFrame - Select dataframe rows based on values in another dataframe Python DataFrame - Select dataframe rows based on values in a column of same dataframe - Python DataFrame - Select dataframe rows based on values in a column of same dataframe Pandas dataframe select 多行基于其中一列中的多个最大值 - Pandas dataframe select multiple rows based on multiple max values in one of the columns 根据 dataframe 中的排序值旋转多行 - Pivoting multiple rows based on sorted values in dataframe 根据多行的值拆分 pandas dataframe - Split a pandas dataframe based on values of multiple rows 根据初始行中的值将熊猫数据帧的多行合并为一行,向该行添加新列的最有效方法? - Most efficient way to merge multiple rows of a pandas dataframe in to one row, adding new columns to the row, based on values in the initial rows? 如何根据 Pandas Dataframe 中的值将多行合并为一行? - How can I consolidate multiple rows into a single row based off their values in a Pandas Dataframe? Pandas DataFrame根据名称在列表中指定的多列的值选择行 - Pandas DataFrame select rows based on values of multiple columns whose names are specified in a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM