根据日期列表过滤数据框

时间:2020-06-02 14:23:42

标签: python dataframe

我有以下气象站数据框(短数据框):

      import pandas as pd
      import numpy as np

      df_Station = pd.DataFrame({'Hemisphere': ['North', 'North', 'North', 'South'], 
                                 'Qtd_Instrumentation': [18, 5, 25, 10],
                                  'Year_Construction': [2015, 2008, 2016, 2020]})

我想生成一个新的数据框。这需要按车站的建造年份进行过滤。我试图创建一个包含目标年份的列表,并按如下所示构建df _:

      list_years = [2015, 2016, 2017, 2018, 2019, 2020] 
      df_Filter =  df_Station[df_Station['Year_Construction'] == list_years]    

但是,此代码有错误:ValueError:长度必须匹配才能进行比较

我希望输出(df_Filter)为:

            print(df_Filter)

            Hemisphere  Qtd_Instrumentation Year_Construction
               North            18              2015
               North            25              2016
               South            10              2020

谢谢。

2 个答案:

答案 0 :(得分:1)

使用pandas.Series.isin进行此类过滤。

df_Filter =  df_Station[df_Station['Year_Construction'].isin(list_years)]

答案 1 :(得分:-1)

import pandas as pd

df_Station = pd.DataFrame({'Hemisphere': ['North', 'North', 'North', 'South'],
                           'Qtd_Instrumentation': [18, 5, 25, 10],
                           'Year_Construction': [2015, 2008, 2016, 2020]})

list_years = [2015, 2016, 2017, 2018, 2019, 2020]
df_Filter = df_Station[df_Station['Year_Construction'].isin(list_years)]

print(df_Filter)

输出

  Hemisphere  Qtd_Instrumentation  Year_Construction
0      North                   18               2015
2      North                   25               2016
3      South                   10               2020