日期和时间的连接时间列和索引的分配

时间:2017-08-07 04:56:42

标签: python pandas date datetime

我有这个数据

               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

我将日期和时间结合起来

                 Datetime  
0     2013-07-09 07:00:00  
1     2013-07-09 08:00:00 

所以我想将DateTime替换为我的数据中的日期和时间以及它的索引。我期望的结果看起来像这样

Datetime     Time     Open     High      Low    Close  Volume

这是我的代码

import pandas as pd

df = pd.read_csv(r"C:\Users\Administrator\Desktop\Csv for PYthon\USDJPY60.csv")
df['Datetime'] = pd.to_datetime(df['Date'].apply(str)+' '+df['Time'])
print(df)

1 个答案:

答案 0 :(得分:1)

您只能在read_csv中使用参数index_colparse_dates

df = pd.read_csv(r"C:\Users\Administrator\Desktop\Csv for PYthon\USDJPY60.csv"), 
                   index_col=['Date_Time'],
                   parse_dates=[['Date','Time']])

print (df)
                        Open     High      Low    Close  Volume
Date_Time                                                      
2013-07-09 07:00:00  101.056  101.151  101.016  101.130    1822
2013-07-09 08:00:00  101.130  101.257  101.128  101.226    2286
2013-07-09 09:00:00  101.226  101.299  101.175  101.180    2685
2013-07-09 10:00:00  101.178  101.188  101.019  101.154    2980

但如果需要Time列:

df = pd.read_csv(r"C:\Users\Administrator\Desktop\Csv for PYthon\USDJPY60.csv"), 
                   index_col=['Date'],
                   parse_dates=['Date'])

df.index = df.index + pd.to_timedelta(df['Time'] + ':00')
print (df)
                      Time     Open     High      Low    Close  Volume
2013-07-09 07:00:00   7:00  101.056  101.151  101.016  101.130    1822
2013-07-09 08:00:00   8:00  101.130  101.257  101.128  101.226    2286
2013-07-09 09:00:00   9:00  101.226  101.299  101.175  101.180    2685
2013-07-09 10:00:00  10:00  101.178  101.188  101.019  101.154    2980

仅限索引(两列均未更改):

df.index = pd.to_datetime(df['Date']+' '+df['Time'])
print (df)
                           Date   Time     Open     High      Low    Close  \
2013-07-09 07:00:00  2013.07.09   7:00  101.056  101.151  101.016  101.130   
2013-07-09 08:00:00  2013.07.09   8:00  101.130  101.257  101.128  101.226   
2013-07-09 09:00:00  2013.07.09   9:00  101.226  101.299  101.175  101.180   
2013-07-09 10:00:00  2013.07.09  10:00  101.178  101.188  101.019  101.154   

                     Volume  
2013-07-09 07:00:00    1822  
2013-07-09 08:00:00    2286  
2013-07-09 09:00:00    2685  
2013-07-09 10:00:00    2980