Add column with number of days between dates in DataFrame pandas

前端 未结 4 553
醉话见心
醉话见心 2020-11-28 03:03

I want to subtract dates in \'A\' from dates in \'B\' and add a new column with the difference.

df
          A        B
one 2014-01-01  2014-02-28 
two 2014-         


        
4条回答
  •  一整个雨季
    2020-11-28 03:18

    To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html

    So,

    df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
    df['C'] = (df['B'] - df['A']).dt.days
    

    which returns:

                 A          B   C
    one 2014-01-01 2014-02-28  58
    two 2014-02-03 2014-03-01  26
    

提交回复
热议问题