2013-07-30 72 views
21

這工作(使用熊貓12 DEV)熊貓使用startswith

table2=table[table['SUBDIVISION'] =='INVERNESS'] 

然後我意識到我需要使用選擇字段從數據框中選擇「開頭」自從我錯過了一堆。 所以每大熊貓文檔儘可能接近我可以跟着我試圖

criteria = table['SUBDIVISION'].map(lambda x: x.startswith('INVERNESS')) 
table2 = table[criteria] 

,並得到AttributeError的:「浮動」對象有沒有屬性「startswith」

所以我試着用同樣的結果

的替代語法
table[[x.startswith('INVERNESS') for x in table['SUBDIVISION']]] 

參考http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing 第4節:列表解析和系列的地圖的方法也可以用於產生更復雜的標準:

我錯過了什麼?

+0

莫非你舉一個小例子來證明這一點,我很驚訝,列表理解不會像地圖一樣提高... –

回答

33

可以使用str.startswith數據幀的方法給出更一致的結果:

In [11]: s = pd.Series(['a', 'ab', 'c', 11, np.nan]) 

In [12]: s 
Out[12]: 
0  a 
1  ab 
2  c 
3  11 
4 NaN 
dtype: object 

In [13]: s.str.startswith('a', na=False) 
Out[13]: 
0  True 
1  True 
2 False 
3 False 
4 False 
dtype: bool 

和布爾索引會工作得很好(我更喜歡使用loc,但它不工作只是同):

In [14]: s.loc[s.str.startswith('a', na=False)] 
Out[14]: 
0  a 
1 ab 
dtype: object 

它看起來至少在系列/列的元素之一是float,它不具有startswith方法因此AttributeError的,列表理解應該提出同樣的錯誤...

+0

謝謝你的回覆...似乎並沒有到達那裏試過桌子[ 'SUBDIVISION'] str.startswith('INVERNESS',na = False)並得到表['SUBDIVISION'] str.startswith('INVERNESS',na = False) ^ SyntaxError:invalid syntax想知道如果我沒有導入某些東西必要?如果我嘗試table.loc [table ['SUBDIVISION']。str.startswith('INVERNESS',na = False)]我會得到一個好結果!!我不明白,因爲我的直==條件工作正常 – dartdog

+1

但是我仍然沒有看到以前的嘗試有什麼問題? – dartdog

+0

@dartdog你錯過了一個點。請包括一小部分證明問題的數據(這似乎很難相信:s) –