如何DataFrame基于Python Pandas中某些列的值从中选择行?
在SQL中,我将使用:
SELECT * FROM table WHERE colume_name = some_value
要选择列值等于标量的行some_value,请使用==:
some_value
==
df.loc[df['column_name'] == some_value]
要选择列值可迭代的行some_values,请使用isin:
some_values
isin
df.loc[df['column_name'].isin(some_values)]
结合以下条件&:
&
df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]
注意括号。由于Python的运算符优先级规则,&绑定比<=和更紧密>=。因此,最后一个示例中的括号是必需的。没有括号
<=
>=
df['column_name'] >= A & df['column_name'] <= B
被解析为
df['column_name'] >= (A & df['column_name']) <= B
这导致一个系列的真值是模棱两可的错误。
要选择列值不相等的行 some_value,请使用!=:
!=
df.loc[df['column_name'] != some_value]
isin返回一个布尔系列,因此要选择值不在 in的行,请some_values使用~以下命令对布尔系列求反:
~
df.loc[~df['column_name'].isin(some_values)]
例如,
import pandas as pd import numpy as np df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(), 'B': 'one one two three two two one three'.split(), 'C': np.arange(8), 'D': np.arange(8) * 2}) print(df) # A B C D # 0 foo one 0 0 # 1 bar one 1 2 # 2 foo two 2 4 # 3 bar three 3 6 # 4 foo two 4 8 # 5 bar two 5 10 # 6 foo one 6 12 # 7 foo three 7 14 print(df.loc[df['A'] == 'foo'])
输出
A B C D 0 foo one 0 0 2 foo two 2 4 4 foo two 4 8 6 foo one 6 12 7 foo three 7 14
如果您要包含多个值,请将它们放在列表中(或更普遍地说,是任何可迭代的)并使用isin:
print(df.loc[df['B'].isin(['one','three'])])
A B C D 0 foo one 0 0 1 bar one 1 2 3 bar three 3 6 6 foo one 6 12 7 foo three 7 14
但是请注意,如果您希望多次执行此操作,则先创建索引然后再使用会更有效df.loc:
df = df.set_index(['B']) print(df.loc['one'])
A C D B one foo 0 0 one bar 1 2 one foo 6 12
或者,要包含索引中的多个值,请使用df.index.isin:
df.loc[df.index.isin(['one','two'])]
A C D B one foo 0 0 one bar 1 2 two foo 2 4 two foo 4 8 two bar 5 10 one foo 6 12