python-3.x - 如何将数据框中的多列组合为 Pandas 日期时间格式

标签 python-3.x pandas

我有一个 Pandas 数据框,其值如下
ProcessID1 UserID Date Month Year Time 248 Tony 29 4 2017 23:30:56 436 Jeff 28 4 2017 20:02:19 500 Greg 4 5 2017 11:48:29 我想知道有什么方法可以将日期、月份和年份和时间的列组合到 pd.datetime格式?

最佳答案

使用 to_datetime 带自动转换栏Day,Month,Year添加 time s 转换 to_timedelta :

df['Datetime'] = pd.to_datetime(df.rename(columns={'Date':'Day'})[['Day','Month','Year']]) + \
                 pd.to_timedelta(df['Time'])

另一种解决方案是连接所有列转换为 string首先:
df['Datetime'] = pd.to_datetime(df[['Date','Month','Year', 'Time']]
                   .astype(str).apply(' '.join, 1), format='%d %m %Y %H:%M:%S')
df['Datetime']  = (pd.to_datetime(df['Year'].astype(str) + '-' +
                                  df['Month'].astype(str) + '-' +
                                  df['Date'].astype(str) + ' ' +
                                  df['Time']))
print (df)
   ProcessID1 UserID  Date  Month  Year      Time            Datetime
0         248   Tony    29      4  2017  23:30:56 2017-04-29 23:30:56
1         436   Jeff    28      4  2017  20:02:19 2017-04-28 20:02:19
2         500   Greg     4      5  2017  11:48:29 2017-05-04 11:48:29

最后,如果需要删除这些列:
df = df.drop(['Date','Month','Year', 'Time'], axis=1)
print (df)
   ProcessID1 UserID            Datetime
0         248   Tony 2017-04-29 23:30:56
1         436   Jeff 2017-04-28 20:02:19
2         500   Greg 2017-05-04 11:48:29

关于python-3.x - 如何将数据框中的多列组合为 Pandas 日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49718863/

相关文章:

python - 如何计算数据框中一组分组行中前一个的差异

python - 如何计算 coskew 和 cokurtosis

python - 如何将 python/cython unicode 字符串转换为长整数数组,以进行 levenshtein 编辑距离

python - 基于人脸识别更新标签

python - 无法修改现有逻辑来解析下一页的标题

python - 对整个数据集重复相同的过程

python-3.x - 使用 "pip3 install xgboost"安装时出错

python - 如何从另一个函数访问框架小部件?

python - 我可以将表从 SQL Server (=MS SQL) 导入到 Python/Pandas 数据框中吗?

python : multiple values key in dictionnary to pair of key/value