If there are data frames for "year", "month", "day", and "time" as shown below, and the time is indicated by a numerical value, is there a way to index the date and time (2018-2-10:00)?
YEAR MONTH DAY HR
2018 2 1 0.0
2018 2 1 0.5
2018 2 1 1.0
2018 2 1 1.5
2018 2 1 2.0
The time is 0.5=30 minutes
in 48 frames per day.
Thank you for your cooperation.
If the data frame is:
df=pd.DataFrame([2018,2,1,0.0],
[2018, 2, 1, 0.5],
[2018, 2, 1, 1.0],
[2018, 2, 1, 1.5]],
columns=['YEAR', 'MONTH', 'DAY', 'HR'])
You can convert to datetime type with to_datetime() in Pandas.However, if the column name is 'HR', it will be an error, so I will change it to 'HOUR' and then convert it.There seems to be no problem with the small number of hours.
pd.to_datetime(df.rename(columns={'HR':'HOUR'}))
If you want this to be an index, you can write if there are other columns:
df.index=pd.to_datetime(df[['YEAR', 'MONTH', 'DAY', 'HR']].rename(columns={'HR':'HOUR'}))
import datetime
# Year, Month, Day, Hour,
dt = datetime.datetime(2018,2,1,1)
Can't I use datetime?
It cannot be specified by float, so it should be an appropriate integer.
© 2024 OneMinuteCode. All rights reserved.