【问题标题】:Extract Month and the week of the month [duplicate]提取月份和月份的星期[重复]
【发布时间】:2021-04-08 14:12:58
【问题描述】:

我目前正在处理带有 DateTime 对象的 pandas DataFrame。有没有办法从熊猫日期时间对象中提取月份的月份周?

data = pd.DataFrame(pd.date_range(' 1/ 1/ 2020', periods = 7, freq ='D'))

0  2000-01-01
1  2000-01-02
2  2000-01-03
3  2000-01-04
4  2000-01-05
5  2000-01-06
6  2000-01-07

Expected:

0  2000-01-01       01-01
1  2000-01-02       01-01
2  2000-01-03       01-01
3  2000-01-04       01-01
4  2000-01-05       01-01 
5  2000-01-06       01-01
6  2000-01-07       01-01
7  2000-01-08       01-02 
8  2000-01-09       01-02
9  2000-01-10       01-02

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    基于Week of a month pandas

    data[0].apply(lambda d: f'{d.month:02}-{(d.day-1) // 7 + 1:02}')
    

    应该给

    0    01-01
    1    01-01
    2    01-01
    3    01-01
    4    01-01
    5    01-01
    6    01-01
    7    01-02
    8    01-02
    9    01-02
    

    名称:0,数据类型:对象

    【讨论】:

      【解决方案2】:

      参考Week of a month pandas

      import pandas as pd
      
      data = pd.DataFrame(pd.date_range(' 1/ 1/ 2020', periods = 10, freq ='D'))
      data['WoM'] = data[0].apply(lambda d : str(d.month) + '-0'+str(d.day//8+1))
      print(data)
      

      这给了你:

                 0   WoM
      0 2020-01-01  1-01
      1 2020-01-02  1-01
      2 2020-01-03  1-01
      3 2020-01-04  1-01
      4 2020-01-05  1-01
      5 2020-01-06  1-01
      6 2020-01-07  1-01
      7 2020-01-08  1-02
      8 2020-01-09  1-02
      9 2020-01-10  1-02
      

      【讨论】:

        猜你喜欢
        • 2021-12-16
        • 2019-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-10
        • 2021-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多