Skip to main content
 首页 » 编程设计

Python//Pandas——只选择给定列中满足特定条件的行

2024年10月01日7虾米姐

我有一个数据框:

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] 

我只想将来自 SP、RJ、RS 或 PR 状态 ('Estado:') 的项目放入新数据框中。

我尝试了下面的行:

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

请您参考如下方法:

您需要将[] 添加到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