2017-01-03 49 views
1

我需要抓取列的起始值爲'MA', 'KP'的值。在字符串值上查詢數據幀列

我想我的鏈查詢數據幀這樣:

df.loc[df['REFERRAL_GRP'].str.startswith("KP")==True | df['REFERRAL_GRP'].str.startswith("MA")==True] 

這似乎並沒有工作,因爲列包含pd.nan對象(NULL值)。

由他們自己,查詢工作,我怎麼可以將這兩個查詢合併在一起?

謝謝

這是我的錯誤信息:

Traceback (most recent call last): Debug Probe, prompt 40, line 1 File "c:\Python27\Lib\site-packages\pandas\core\generic.py", line 892, in __nonzero__ .format(self.__class__.__name__)) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

+0

因此,*列名*需要開始任「MA」還是「KP?」那麼你爲什麼試圖抓住以「MA」或「KP」開頭的值?你的問題和嘗試互相矛盾。 – blacksite

+0

是在if,for或其他條件中使用的表達式? – e4c5

回答

1

這是我們看到了很多的問題。

df.loc[ 
    # 2. This returns a whole lot of `True`s or `False`s 
    df['REFERRAL_GRP'].str.startswith("KP")==True 
    # 1. `|` is expecting a `True` or `False` 
    | 
    # 2. This returns a whole lot of `True`s or `False`s 
    df['REFERRAL_GRP'].str.startswith("MA")==True 
] 

用括號包裹條件,修復它

df.loc[ 
    # 1. Series of `True`s or `False`s 
    (df['REFERRAL_GRP'].str.startswith("KP")==True) 
    # 2. `|` is now a operator on `pd.Series` and is expecting `pd.Series` 
    | 
    # 1. Series of `True`s or `False`s 
    (df['REFERRAL_GRP'].str.startswith("MA")==True) 
] 

這麼說,我會做這個

df.loc[df.REFERRAL_GRP.str.match('^KP|MA')] 
2

嘗試numpy的logical_or

import numpy as np 
df.loc[np.logical_or(df['REFERRAL_GRP'].str.startswith("KP")==True , df['REFERRAL_GRP'].str.startswith("MA")==True)] 
+0

我會試試看,謝謝 –