首页 文章

Python从日期开始创建购买月份

提问于
浏览
0

我需要在数据框中创建一个列,从月的22日到下个月的21日 . buymonth应该是这个月的第一天 . 示例:date buymonth 12/17/16 >> 12/01/16 12/23/16 >> 01/01/17

我尝试了很多代码,但在尝试比较大于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]用于datetime / timedelta操作

1 回答

  • 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
    

相关问题