根据 Pandas 中的字符串列表过滤掉行

Filter out rows based on list of strings in Pandas

我有一个大型时间序列数据框(称为 df),前 5 条记录如下所示:

df

         stn     years_of_data  total_minutes avg_daily TOA_daily   K_daily
date                        
1900-01-14  AlberniElementary      4    5745    34.100  114.600 0.298
1900-01-14  AlberniWeather         6    7129    29.500  114.600 0.257
1900-01-14  Arbutus                8    11174   30.500  114.600 0.266
1900-01-14  Arrowview              7    10080   27.600  114.600 0.241
1900-01-14  Bayside                7    9745    33.800  114.600 0.295

目标:

I am trying to remove rows where any of the strings in a list are present in the 'stn' column. So,I am basically trying to filter this dataset to not include rows containing any of the strings in following list.

尝试:

remove_list = ['Arbutus','Bayside']

cleaned = df[df['stn'].str.contains('remove_list')]

Returns:

输出[78]:

stn years_of_data   total_minutes   avg_daily   TOA_daily   K_daily
date    

没有!

我尝试了几种引号、括号甚至 lambda 函数的组合;虽然我是新手,所以可能没有正确使用语法..

使用isin:

cleaned = df[~df['stn'].isin(remove_list)]

In [7]:

remove_list = ['Arbutus','Bayside']
df[~df['stn'].isin(remove_list)]
Out[7]:
                          stn  years_of_data  total_minutes  avg_daily  \
date                                                                     
1900-01-14  AlberniElementary              4           5745       34.1   
1900-01-14     AlberniWeather              6           7129       29.5   
1900-01-14          Arrowview              7          10080       27.6   

            TOA_daily  K_daily  
date                            
1900-01-14      114.6    0.298  
1900-01-14      114.6    0.257  
1900-01-14      114.6    0.241  

有一个类似的问题,找到这个旧线程,我认为还有其他方法可以得到相同的结果。我对@EdChum 针对我的特定应用程序的解决方案的问题是我没有一个可以完全匹配的列表。如果您有同样的问题,.isin 不适用于该应用程序。

相反,您也可以尝试一些选项,包括 numpy.where:

  removelist = ['ayside','rrowview']
  df['flagCol'] = numpy.where(df.stn.str.contains('|'.join(remove_list)),1,0)

请注意,此解决方案实际上并没有删除匹配的行,只是标记了它们。你可以copy/slice/drop随你喜欢。

这个解决方案在您不知道的情况下很有用,例如,如果站名是否大写并且不想事先通过标准化文本。 numpy.where 通常也很快,可能与 .isin 没有太大区别。

我只想将我的 2 美分加到这个非常重要的用例中(过滤出项目列表,按字符串值索引)。 .isin() 方法的参数,不需要是 list!可以是pd.Series!然后你可以这样做:

df[~df['stn'].isin(another_df['stn_to_remove_column_there'])]

明白我的意思了吗?您可以在没有 .to_list() 方法的情况下使用此构造。