select * from table where colume_name = some_value.
我試圖看看熊貓文檔,但沒有當即找到答案。spa
df.loc[df['column_name'] == some_value]
要選擇其列值在可迭代值some_values中的行,請使用isin:code
df.loc[df['column_name'].isin(some_values)]
要選擇列值不等於some_value的行,請使用!=:索引
df.loc[df['column_name'] != some_value]
isin返回一個布爾系列,因此要選擇值不在some_values的行,使用〜來否認布爾系列:three
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'])
產量pandas
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:it
print(df.loc[df['B'].isin(['one','three'])])
產量io
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:table
df = df.set_index(['B']) print(df.loc['one'])
產量class
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