【问题标题】:In Python, Pandas. How to subset dataframe by WOM - 'Week of the Month'?在 Python 中,熊猫。如何按 WOM 对数据框进行子集化 - “本月的一周”?
【发布时间】:2014-12-02 03:40:38
【问题描述】:

我希望能够按月中的周对 df 进行子集化,类似于您可以对周或月中的某天执行的操作。

sample = df[df.index.month == 12] 

那么有什么办法可以做到吗?

sample = df[df.index.WOM == 1]

我知道如果我输入上面的行,你会得到 AttributeError: 'Index' object has no attribute 'WOM',仅供参考以了解我想要做什么。

谢谢

【问题讨论】:

    标签: python pandas indexing dataframe


    【解决方案1】:

    您可以查看.weekofyear 的值和月初相同的值,这两者的差异应该给出月份的星期几;例如:

    >>> days = ['2014-02-01', '2014-06-10', '2014-08-30', '2014-11-22']
    >>> idx = pd.to_datetime(days)
    >>> idx.weekofyear
    array([ 5, 24, 35, 47], dtype=int32)
    

    在月初,您可以从索引本身中减去 .day

    >>> mon = idx - pd.to_timedelta(idx.day - 1, unit='D')
    >>> mon.weekofyear
    array([ 5, 22, 31, 44], dtype=int32)
    

    一个月的星期是:

    >>> 1 + idx.weekofyear - mon.weekofyear
    array([1, 3, 5, 4], dtype=int32)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      相关资源
      最近更新 更多