【问题标题】:Pandas: Add column with date熊猫:添加日期列
【发布时间】:2021-03-25 14:38:49
【问题描述】:

我对 Python 和 Pandas 非常陌生,希望能获得一些帮助,使用 for 循环为 Date 添加一列。我已经尝试了下面的代码,以及该代码的一些变体,但总是收到错误。我为“Day”添加了一个列,这样我就可以返回一个日期;但后来我删除了该列。

对于 SAP Period = 0 的行,我想返回 1/1/YYYY。对于所有其他行,我想返回该月的最后一天。

for y in df_BW['SAP Period']:
    if y == 0:
        df_BW['Period'] = pd.to_datetime(df_BW[['Day', 'SAP Period2', 'Year']].astype(str).apply(' '.join, 1), format='%d %m %Y')
    else:
        df_BW['Period'] = pd.to_datetime(df_BW[['Day', 'SAP Period', 'Year']].astype(str).apply(' '.join, 1), format='%d %m %Y') + MonthEnd()
Year SAP Period Date
2020 0 1/1/2020
2020 1 1/31/2020
2020 2 2/29/2020
2020 0 1/1/2020
2020 2 2/29/2020
2020 2 2/29/2020
2020 3 3/31/2020
2020 12 12/31/2020
2021 0 1/1/2021
2021 1 1/31/2021
2021 3 3/31/2021
2021 0 1/1/2021
2021 2 2/28/2021
2021 3 3/31/2021

【问题讨论】:

    标签: python pandas python-datetime


    【解决方案1】:

    使用np.whereMonthEnd 来自pandas.teseries.offset.MonthEnd

    from pandas.tseries.offsets import MonthEnd
    
    df['date'] = pd.to_datetime(df['Year'].astype(str) + 
                  df['SAP Period'].replace(0,1).astype(str).str.zfill(2) + 
                 '01',format='%Y%m%d')
    
    df['date'] = np.where(df['SAP Period'].ne(0), df['date'] + MonthEnd(1), df['date'])
    
    
        Year  SAP Period        Date       date
    0   2020           0    1/1/2020 2020-01-01
    1   2020           1   1/31/2020 2020-01-31
    2   2020           2   2/29/2020 2020-02-29
    3   2020           0    1/1/2020 2020-01-01
    4   2020           2   2/29/2020 2020-02-29
    5   2020           2   2/29/2020 2020-02-29
    6   2020           3   3/31/2020 2020-03-31
    7   2020          12  12/31/2020 2020-12-31
    8   2021           0    1/1/2021 2021-01-01
    9   2021           1   1/31/2021 2021-01-31
    10  2021           3   3/31/2021 2021-03-31
    11  2021           0    1/1/2021 2021-01-01
    12  2021           2   2/28/2021 2021-02-28
    13  2021           3   3/31/2021 2021-03-31
    

    【讨论】:

      【解决方案2】:

      试试这个:

      from pandas.tseries.offsets import MonthEnd
      
      df['Date'] = df.apply(lambda x: pd.to_datetime('1/1/' + str(x['Year'])) + MonthEnd(x['SAP Period']),axis=1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-03
        • 2020-12-01
        • 2017-11-03
        • 2017-05-22
        • 2018-03-09
        • 2021-07-25
        • 2022-01-07
        • 2018-07-25
        相关资源
        最近更新 更多