pandas
  • dataframe
  • filter
  • 2017-11-08 9 views 1 likes 
    1

    "nativecountry"列の "United-States"という値を持つ行のデータフレームをフィルタリングしたいとします。これは簡単なことのようですが、私が試したことは失敗しました。ここではデータフレームを作成するための私のコードだ:列の特定の値を持つ列のPandasデータフレーム

    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. 
    

    任意の考えを?ありがとう。そのためnativecountryの値の

    +0

    米国 - 米国のスペースインフロントがあります。この小さなトリックをすることでこれを見ることができます。 'df_adult.head()。to_dict()' –

    答えて

    1

    では、次の操作を行うことができ、先頭のスペースがあります。

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

    パーフェクト、ありがとう! –

    +0

    これはいい人です:-) – Wen

    +0

    @ChrisWoodruffこのアンバーがあなたを助けたとしたら、[受け入れ](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer -work?answertab = votes#tab-top)。ありがとうございました。 –

    関連する問題