Home > database >  How to convert pandas date column to numeric
How to convert pandas date column to numeric

Time:02-24

Let say I have following code

import pandas as pd
df = pd.DataFrame([[pd.to_datetime('2019-01-01').to_period('M'), pd.to_datetime('2019-01-01').to_period('M')], [pd.to_datetime('2019-01-01').to_period('M'), pd.to_datetime('2019-01-01').to_period('M')], [pd.to_datetime('2019-01-01').to_period('M'), pd.to_datetime('2019-01-01').to_period('M')]], columns = ['date1', 'date2'])
df['dat3'] = df['date1'] - df['date2']
print(df)
     date1    date2             dat3
0  2019-01  2019-01  <0 * MonthEnds>
1  2019-01  2019-01  <0 * MonthEnds>
2  2019-01  2019-01  <0 * MonthEnds>

Is there any way to have the elements of dat3 as number/integer so that I can perform numerical calculation with that column?

CodePudding user response:

One option is to directly use .n attribute in side a map:

df.dat3.map(lambda t: t.n)

0    0
1    0
2    0
Name: dat3, dtype: int64
  • Related