pandas 如何组合日期列和时间列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45538912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:11:39  来源:igfitidea点击:

How to combine date column and time column

pythonpandasdatedatetime

提问by Korn Tawe

I have data look like this

我有数据看起来像这样

        Date        Time     Open     High      Low    Close  Volume
0      2013.07.09   7:00  101.056  101.151  101.016  101.130    1822
1      2013.07.09   8:00  101.130  101.257  101.128  101.226    2286
2      2013.07.09   9:00  101.226  101.299  101.175  101.180    2685
3      2013.07.09  10:00  101.178  101.188  101.019  101.154    2980
4      2013.07.09  11:00  101.153  101.239  101.146  101.188    2623

How to combine Date column and Time column into one column which is Date Time. And I wonder if i do that whether I have to change the string to date. Thank in advance.

如何将日期列和时间列合并为一列,即日期时间。我想知道我是否这样做是否必须将字符串更改为日期。预先感谢。

回答by Bharath

If you have 'Date' column as timestamp then you convert them to a string and add them , then convert them into timestamp i.e

如果您将“日期”列作为时间戳,则将它们转换为字符串并添加它们,然后将它们转换为时间戳,即

df['Datetime'] = pd.to_datetime(df['Date'].apply(str)+' '+df['Time'])

Output :

输出 :

        Date   Time     Open     High      Low    Close  Volume  \
0 2013-07-09   7:00  101.056  101.151  101.016  101.130    1822   
1 2013-07-09   8:00  101.130  101.257  101.128  101.226    2286   
2 2013-07-09   9:00  101.226  101.299  101.175  101.180    2685   
3 2013-07-09  10:00  101.178  101.188  101.019  101.154    2980   
4 2013-07-09  11:00  101.153  101.239  101.146  101.188    2623   

             Datetime  
0 2013-07-09 07:00:00  
1 2013-07-09 08:00:00  
2 2013-07-09 09:00:00  
3 2013-07-09 10:00:00  
4 2013-07-09 11:00:00  

回答by R.A.Munna

dataframe["Date Time"] = dataframe["Date"].map(str) + dataframe["Time"]

Update

更新

Formatting the date you can use

格式化您可以使用的日期

dataframe["Date Time"] =pd.to_datetime(dataframe["Date"].map(str) +'-'+ dataframe["Time"])

and instead of replace you can delete those Dateand Timecolumn from the dataframe. like this

而不是替换,您可以从数据框中删除那些DateTime列。像这样

del dataframe["Date"], dataframe["Time"]