Home > other >  Python - Pandas, Datetime - Convert datetime entries over 3 date columns into month values (i.e. 202
Python - Pandas, Datetime - Convert datetime entries over 3 date columns into month values (i.e. 202

Time:06-14

Having trouble converting datetime entries to month values over 3 columns in my dataframe.

What i have tried is writing a lambda function: lambda x: x.strftime('%m') if isinstance(x , datetime.datetime) else x

and using .apply to apply it: df.apply(lambda x: x.strftime('%m') if isinstance(x , datetime.datetime) else x)

I seem to be getting no change to my dataset.

desired outcome is to go from this;

date 1 date 2 date 3
2022-05-26 00:00:00 2022-05-31 00:00:00 2022-06-05 00:00:00
2022-06-01 00:00:00 2022-06-13 00:00:00 2022-07-05 00:00:00

to this;

date 1 date 2 date 3
05 05 06
06 06 07

Thanks in advance, I'm still on my training wheels...

Kind Regards, Mike.

CodePudding user response:

Use Series.dt.strftime per columns in lambda function in DataFrame.apply:

df1 = df.apply(lambda x: x.dt.strftime('%m'))
print (df1)
  date 1 date 2 date 3
0     05     05     06
1     06     06     07

Your solution is possible if elementwise use lambda function in DataFrame.applymap, but it is not vectorized:

df1 = df.applymap(lambda x: x.strftime('%m') if isinstance(x , pd.Timestamp) else x)

If need months names:

df2 = df.apply(lambda x: x.dt.month_name())
print (df2)
  date 1 date 2 date 3
0    May    May   June
1   June   June   July

CodePudding user response:

Would you try this?

for col in df.columns:
    df[col] = pd.to_datetime(df[col]).dt.strftime('%m')
print(df)

  date1 date2 date3
0    05    05    06
1    06    06    07
  • Related