[Python] Use pandas to merge year, month, day and hour columns into time format columns

There is a set of data as shown in the figure. Now I want to merge the year, month, day, and hour into a format similar to 2021-05-01 00:00:00. Use the pands library to merge the data and convert the format. The code is as follows
insert image description here
:

import pandas as pd

#读取数据文件
df = pd.read_csv('history_data/testout.csv')

#这里先把年月日合并转换格式为time,放入date列中
df['date'] = df['year'].map(str)+"/"+df['mouth'].map(str)+"/"+df['day'].map(str)
pd.to_datetime(df['date'])
#date列已经有年月日的数据,加上整数类型的小时数据转换为00:00:00的格式,将小时数据设为时间索引并合并
df['date_time'] = pd.to_datetime(df['date']) + pd.TimedeltaIndex(df['hour'],unit='H')
#删除不全的过渡列date
df=df.drop(['date'],axis=1)

#打印查看效果
print(df['date_time'])
#将结果输出在另一个csv文件中
filename='history_data/testout2.csv'
df.to_csv(filename)

The combined effect is shown in the figure:
insert image description here

Guess you like

Origin blog.csdn.net/qq_45742383/article/details/126473107