2017-08-07 39 views
0

我有這樣的數據級聯日期和時間列和分配的索引

   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  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

您可以使用參數index_colparse_datesread_csv

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 
+0

語法錯誤:無效的語法 –

+0

什麼回報無效的語法?你使用什麼解決方案? – jezrael

+0

@jezrael大聲笑......當OP想要幫助,但不願意幫助你幫助他們 –