简体   繁体   中英

I want to add two df columns df['Date'] and df['hour'] to create the column timestamp

The problem is the hour column and the date column are like this:

[在此处输入图片说明

Is there any way to add them to get a column starting with 2019-07-01 7:00:00 and so on

You can do:

df['datetime'] = pd.to_datetime(df['Date']) + pd.to_timedelta('1H') * df['Hour']

# or
# df['datetime'] = pd.to_datetime(df['Date']) + pd.to_timedelta(df['Hour'], unit='H')
df['datetime'] = df[['Date', 'hour']].apply(lambda x: ' '.join(x), axis=1)

然后:

df['datetime']= pd.to_datetime(df['datetime'])


You can try something like this

df.apply(lambda t : pd.datetime.combine(t['date_column_name'],t['time_column_name']),1)

If both columns are string you can simply concatenate it as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM