筛选具有特定列值的行的Pandas数据帧

时间:2017-11-08 22:39:58

标签: pandas dataframe filter

我想在“nativecountry”列中过滤值为“United-States”的行的数据帧。这似乎是一件简单的事情,但我尝试过的事情都失败了。这是我创建数据框的代码:

import pandas as pd

url = 'https://archive.ics.uci.edu/ml/machine-learning-
       databases/adult/adult.data'
col_names = ['age', 'workclass', 'fnlwgt', 'education', 'educationnum', 
             'maritalstatus', 'occupation', 'relationship',
             'race', 'sex', 'capitalgain', 'capitalloss', 
             'hoursperweek', 'nativecountry', 'income']
df_adult = pd.read_csv(url, header = None, names = col_names)

我尝试过以下方法来过滤'美国'的'nativecountry':

#This returns an empty dataframe
df_US = df_adult[df_adult["nativecountry"] == 'United-States']
#Code from this source: https://chrisalbon.com/python/pandas_index_select_and_filter.html

#This returns the error: name 'United' is not defined
df_US = df_adult.query("nativecountry == United-States")
#Code from this source: https://pythonspot.com/en/pandas-filter/

#And this doesn't work either, for some reason
df_adult.useSQLInstead(SELECT * FROM df_adult WHERE nativecountry=United-States)
...just kidding.

有什么想法?感谢。

1 个答案:

答案 0 :(得分:1)

由于nativecountry的值具有前导空格,您可以执行以下操作:

df_adult[df_adult['nativecountry'].str.contains('United-States')]