【问题标题】:How to extract a specific month and day from all the years in Pandas?如何从 Pandas 的所有年份中提取特定的月份和日期?
【发布时间】:2020-10-11 06:10:29
【问题描述】:

我的数据集是这样的

            CPI
DATE    
1950-01-01  NaN
1950-02-01  1.004254
1950-03-01  1.005530
1950-04-01  1.005955
1950-05-01  1.011059
... ...
2020-01-01  1.001455
2020-02-01  1.002345
2020-03-01  0.998100
2020-04-01  0.990164
2020-05-01  0.989646

我想从“XXXX-01-01”中提取每年的所有数据。并将它们放入一个新的数据集中。谁能举例说明如何做到这一点?

【问题讨论】:

    标签: python pandas timestamp time-series


    【解决方案1】:

    你可以试试:

    new_df = df.loc[(df.DATE.dt.month == 1) & (df.DATE.dt.day == 1)]
    

    【讨论】:

    • 对不起,我是 Pandas 的新手,我试过你的方法,它显示错误 ''DataFrame' object has no attribute 'DATE''
    • @Flyingpig:由于DATE是DataFrame的索引,所以你必须调用new_df = df.loc[(df.index.month == 1) & (df.index.day == 1)]
    【解决方案2】:

    你也可以使用query

    df.query("index.dt.month.eq(1) and index.dt.day.eq(1)")
    

    假设你有 Datetimeindex 类型的索引,如果不是首先转换它 Datetimeindex 使用 df.index = pd.to_datetime(df.index)

    【讨论】:

      猜你喜欢
      • 2017-01-19
      • 2021-10-02
      • 2018-02-16
      • 1970-01-01
      • 2021-04-02
      • 2014-09-28
      相关资源
      最近更新 更多