【问题标题】:Python to create buy month from datePython从日期创建购买月份
【发布时间】:2017-06-03 02:13:26
【问题描述】:

我需要在数据框中为从当月 22 日到下个月 21 日的购买月份创建一列。 buymonth 应该是该月的第一天。 例子: 购买日期 16 年 12 月 17 日 >> 16 年 12 月 1 日 2016 年 12 月 23 日 >> 17 年 1 月 1 日

我尝试了很多代码,但在尝试比较大于 21 的日期时总是出错

If df.loc[:,'date'].dt.day > 21:

抛出错误 ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

tmp2["buymonth"] = tmp2['date'] + relativedelta(months=+1)

给我错误 TypeError:日期时间/时间增量操作的类型 [object] 不兼容

【问题讨论】:

    标签: python


    【解决方案1】:

    使用 np.where 和 pandas 的日期偏移功能。

    import pandas as pd
    from pandas.tseries.offsets import MonthBegin
    
    df = DataFrame({'date' : pd.date_range('1/1/2010', periods=365)})
    df.loc[:, 'buymonth'] = np.where(df.loc[:,'date'].dt.day > 21, 
            df.loc[:,'date'] + MonthBegin(1), 
            df.loc[:,'date'] + MonthBegin(1) - MonthBegin(1))
    
    df.iloc[20:30]
    Out[9]: 
             date   buymonth
    20 2010-01-21 2010-01-01
    21 2010-01-22 2010-02-01
    22 2010-01-23 2010-02-01
    23 2010-01-24 2010-02-01
    24 2010-01-25 2010-02-01
    25 2010-01-26 2010-02-01
    26 2010-01-27 2010-02-01
    27 2010-01-28 2010-02-01
    28 2010-01-29 2010-02-01
    29 2010-01-30 2010-02-01
    

    【讨论】:

    • 谢谢。我确实必须使用 pd.DatetimeIndex 将“日期”添加到 pd.offsets.MonthBegin(1) df.loc[:, 'buymonth'] = np.where(df.loc[:,'date'] .dt.day > 21, pd.DatetimeIndex(df.loc[:,'date']) + pd.offsets.MonthBegin(1), pd.DatetimeIndex(df.loc[:,'date']) + pd. offsets.MonthBegin(1) - pd.offsets.MonthBegin(1))
    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    相关资源
    最近更新 更多