aabujamra
aabujamra

Reputation: 4636

Python // Pandas - only select the rows that have certain conditions in a given column

I have a dataframe:

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]

I want to put in a new dataframe only the items that are from the state ('Estado:') of SP, RJ, RS or PR.

I tried the line below:

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

However it is bringing me a very limited list and all the items have Estado: are 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]

Can someone help?

EDIT:

I try isin, but get error:

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

Upvotes: 3

Views: 2364

Answers (1)

jezrael
jezrael

Reputation: 862601

You need add [] to isin, because parameter values is:

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

Upvotes: 4

Related Questions