繁体   English   中英

根据日期列表过滤 dataframe

[英]Filter the dataframe according to a list of dates

我有以下 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]})

我想生成一个新的 dataframe。 这需要在车站建成的年份进行过滤。 我试图创建一个包含目标年份的列表并构建 df_ 如下:

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

但是,此代码有错误: ValueError: Lengths must match to compare

我希望 output (df_Filter) 为:

            print(df_Filter)

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

谢谢你。

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

df_Filter =  df_Station[df_Station['Year_Construction'].isin(list_years)]
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)

Output

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM