[英]pandas - combine time and date from two dataframe columns to a datetime column
This is a follow up question of the accepted solution in here .这是此处接受的解决方案的后续问题。
I have a pandas dataframe:我有一个 pandas dataframe:
In one column 'time' is the time stored in the following format: ' HHMMSS
' (eg 203412 means 20:34:12).在一列中,“时间”是以下列格式存储的时间:“ HHMMSS
”(例如 203412 表示 20:34:12)。
In another column 'date' the date is stored in the following format: ' YYmmdd
' (eg 200712 means 2020-07-12).在另一列“日期”中,日期以以下格式存储:“ YYmmdd
”(例如 200712 表示 2020-07-12)。 YY
represents the addon to the year 2000. YY
代表对 2000 年的附加。
Example:例子:
import pandas as pd
data = {'time': ['123455', '000010', '100000'],
'date': ['200712', '210601', '190610']}
df = pd.DataFrame(data)
print(df)
# time date
#0 123455 200712
#1 000010 210601
#2 100000 190610
I need a third column which contains the combined datetime format (eg 2020-07-12 12:34:55
) of the two other columns.我需要第三列,其中包含其他两列的组合日期时间格式(例如2020-07-12 12:34:55
)。 So far, I can only modify the time but I do not know how to add the date.到目前为止,我只能修改时间,但我不知道如何添加日期。
df['datetime'] = pd.to_datetime(df['time'], format='%H%M%S')
print(df)
# time date datetime
#0 123455 200712 1900-01-01 12:34:55
#1 000010 210601 1900-01-01 00:00:10
#2 100000 190610 1900-01-01 10:00:00
How can I add in column df['datetime']
the date from column df['date']
, so that the dataframe is:如何在df['datetime']
列中添加df['date']
列中的日期,以便 dataframe 为:
time date datetime
0 123455 200712 2020-07-12 12:34:55
1 000010 210601 2021-06-01 00:00:10
2 100000 190610 2019-06-10 10:00:00
I found this question , but I am not exactly sure how to use it for my purpose.我发现了这个问题,但我不确定如何将它用于我的目的。
You can join columns first and then specify formar:您可以先连接列,然后指定格式:
df['datetime'] = pd.to_datetime(df['date'] + df['time'], format='%y%m%d%H%M%S')
print(df)
time date datetime
0 123455 200712 2020-07-12 12:34:55
1 000010 210601 2021-06-01 00:00:10
2 100000 190610 2019-06-10 10:00:00
If possible integer columns:如果可能 integer 列:
df['datetime'] = pd.to_datetime(df['date'].astype(str) + df['time'].astype(str), format='%y%m%d%H%M%S')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.