Skip to content Skip to sidebar Skip to footer

Converting A Datetime Column To A DatetimeIndex In Pandas

There are so many questions that revolve around converting dates to a datetimeindex. I personally need a datetimeindex to work with the Calmap package that requires the datetimeind

Solution 1:

Try concat Date and Time before setting index. Use df.column.str.cat(colum1, sep=' ')

print(df)

     Name     Time     Date
0  FName LName  12:00PM  10/5/20
1  FName LName  12:00PM  10/5/20
2  FName LName  12:00PM  10/5/20
3  FName LName  12:00PM  10/5/20
4  FName LName  12:00PM  10/5/20
5  FName LName  12:00PM  10/5/20
6  FName LName  12:00PM  10/5/20


df['datetime']=pd.to_datetime(df['Date'].str.cat(df.Time, sep=' '))
df.set_index(df['datetime'], inplace=True)
print(df)

            

                      Name     Time     Date            datetime
datetime                                                              
2020-10-05 12:00:00  FName LName  12:00PM  10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00  FName LName  12:00PM  10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00  FName LName  12:00PM  10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00  FName LName  12:00PM  10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00  FName LName  12:00PM  10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00  FName LName  12:00PM  10/5/20 2020-10-05 12:00:00
2020-10-05 12:00:00  FName LName  12:00PM  10/5/20 2020-10-05 12:00:00

Post a Comment for "Converting A Datetime Column To A DatetimeIndex In Pandas"