2017-06-21 105 views
1

我有一個數據幀:的Python //熊貓 - 只選擇具有給定列一定條件的行

df: 

    Estado:      Telefone 
0  SP (11) 2162-0660/(11) 2162-0639 
1  RJ     (11) 3144-4000 
2  SC     (62) 3878-8150 
3  RS     (11) 4593-7403 
4  PR (19) 3313-5680/(19) 3313-6000 
5  PE     (81) 3316-0586 
6  GO     (19) 3423-8000 
... 
[379 rows x 2 columns] 

我想提出一個新的數據幀僅是從國家項目('Estado:' )SP,RJ,RS或PR。

我想下面的一行:

lista=lista.loc[lista['Estado:'] == ('RJ' or 'SP' or 'PR' or 'RS')] 

但是它帶給我一個非常有限的名單,所有的項目都Estado:RJ

lista: 

    Estado:      Telefone 
16  RJ     (31) 3263-9664 
47  RJ     (21) 3575-0600 
48  RJ     (21) 3221-0000 
60  RJ     (11) 2118-9500 
69  RJ (21) 2677-1077/(21) 2252-1989 
82  RJ     (21) 3224-8091 
83  RJ        NaN 
105  RJ (24) 2233-1877/(24) 2233-1874 
140  RJ     (31) 3660-9100 
143  RJ     (21) 2277-2000 
175  RJ     (21) 3435-1002 
216  RJ     (21) 9428-1902 
218  RJ (21) 2142-1482/(21) 2142-1480 
235  RJ     (11) 3468-2098 
274  RJ        NaN 
315  RJ     (21) 2676-9196 
[16 rows x 2 columns] 

有人可以幫忙嗎?

編輯:

我嘗試isin,但得到的錯誤:

TypeError: isin() takes 2 positional arguments but 5 were given

+2

使用['isin'](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html) - 'LISTA = LISTA [LISTA ['埃斯塔:']。isin(['RJ','SP','PR','RS'])]' – jezrael

+1

我檢查了幾個與isin有關的帖子,並且實際嘗試了它,但是他們沒有解釋如何使用它與多個項目(我收到一些錯誤,如'isin只接受兩個參數,你有四個'。隨着你的提示,我發現我應該使用這些括號,它的工作。 TKS! – abutremutante

+1

超級,gald可以幫助!祝你好運! – jezrael

回答

1

您需要添加[]isin,因爲參數values是:

values : set or list-like

The sequence of values to test. Passing in a single string will raise a TypeError. Instead, turn a single string into a list of one element.

lista=lista[lista['Estado:'].isin(['RJ' , 'SP' , 'PR' , 'RS'])] 
print (lista) 
    Estado:       Telefone 
0  SP (11) 2162-0660/(11) 2162-0639 
1  RJ     (11) 3144-4000 
3  RS     (11) 4593-7403 
4  PR (19) 3313-5680/(19) 3313-6000 

lista=lista[lista['Estado:'].isin('RJ' , 'SP' , 'PR' , 'RS')] 
print (lista) 

TypeError: isin() takes 2 positional arguments but 5 were given