2017-03-06 86 views
2

我想從數據框contributors其中職業退休,像這樣的所有行:大熊貓 - 在一個數據幀中選擇行使用字符串平等

mask = (contributors.contbr_occupation.str == 'RETIRED') 
print(contributors[mask]) 

不過,我得到堆棧跟蹤如下:

Traceback (most recent call last): 
    File "C:\Users\Me\Anaconda3\envs\pandas\lib\site-packages\pandas\indexes\base.py", line 2134, in get_loc 
    return self._engine.get_loc(key) 
    File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433) 
    File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279) 
    File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742) 
    File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696) 
KeyError: False 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "census_attack.py", line 27, in <module> 
    print(contributors[mask]) 
    File "C:\Users\Me\Anaconda3\envs\pandas\lib\site-packages\pandas\core\frame.py", line 2059, in __getitem__ 
    return self._getitem_column(key) 
    File "C:\Users\Me\Anaconda3\envs\pandas\lib\site-packages\pandas\core\frame.py", line 2066, in _getitem_column 
    return self._get_item_cache(key) 
    File "C:\Users\Me\Anaconda3\envs\pandas\lib\site-packages\pandas\core\generic.py", line 1386, in _get_item_cache 
    values = self._data.get(item) 
    File "C:\Users\Me\Anaconda3\envs\pandas\lib\site-packages\pandas\core\internals.py", line 3543, in get 
    loc = self.items.get_loc(item) 
    File "C:\Users\Me\Anaconda3\envs\pandas\lib\site-packages\pandas\indexes\base.py", line 2136, in get_loc 
    return self._engine.get_loc(self._maybe_cast_indexer(key)) 
    File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433) 
    File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279) 
    File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742) 
    File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696) 
KeyError: False 

我該怎麼做?

回答

1

如果你只是實際執行平等檢查(不圍堵或類似的東西),不使用str訪問 - 你不需要它。

mask = (contributors.contbr_occupation == 'RETIRED') 

>>> df 

    strings 
0  abc 
1  def 
2  ghi 
3  abc 

>>> df[df.strings == 'abc'] 

    strings 
0  abc 
3  abc 

如果你需要一個像遏制一些邏輯條件,實際上是呼籲str訪問一個字符串的方法,例如用str.contains

mask = (contributors.contbr_occupation.str.contains('RETIRED')) 
2

你可以使用query

contributors.query('contbr_occupation == "RETIRED"') 
+0

是的,當事情安定下來時,我可以再次進入節奏。 – piRSquared