如何根据列值的 "or" 运算符在数据框中 select 行
How to select rows in a dataframe based on an "or" operator of values of a column
假设我有一个包含变量 'Age'
.
的数据框 df
我知道如果我想 select 行 'Age' >= 25
和 'Age' <= 35
那么我可以使用:
df1 = df[(df['Age']>=25) & (df['Age']<=35)]
如果我想 select 行 'Age' <= 10
或 'Age' >= 40
怎么办?是否有一个等价的 or
符号,就像 and
符号是 &
一样?我试过下面的代码,但它不起作用:
df1 = df[(df['Age']<=10) or (df['Age']>=40)]
您可以使用 OR 运算符 | (管道)。来自 pandas 文档。
Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.
http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing
这对我有用
df1 = df[(df['Age']<=10) | (df['Age']>=40)]
假设我有一个包含变量 'Age'
.
df
我知道如果我想 select 行 'Age' >= 25
和 'Age' <= 35
那么我可以使用:
df1 = df[(df['Age']>=25) & (df['Age']<=35)]
如果我想 select 行 'Age' <= 10
或 'Age' >= 40
怎么办?是否有一个等价的 or
符号,就像 and
符号是 &
一样?我试过下面的代码,但它不起作用:
df1 = df[(df['Age']<=10) or (df['Age']>=40)]
您可以使用 OR 运算符 | (管道)。来自 pandas 文档。
Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.
http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing
这对我有用
df1 = df[(df['Age']<=10) | (df['Age']>=40)]