Python 日期和时间列的串联以及对索引的赋值
我有这些数据Python 日期和时间列的串联以及对索引的赋值,python,pandas,date,datetime,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
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替换为Date和Time。我期望的结果是这样的
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)
您只能在以下位置使用参数index_col和parse_dates:
但如果需要时间列:
仅对于索引,两列均未更改:
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
SyntaxError:无效的syntaxwhat返回无效语法?你用什么解决办法?@jezrael Lol。。。当OP需要帮助但不愿意帮助他们时,运行文件'C:/Users/Administrator/Documents/Downloads/Compressed/course3_Downloads/untitled7.py',wdir='C:/Users/Administrator/Documents/Downloads/Compressed/course3_Downloads/untitled7.py',wdir='C:/Users/Administrator/Documents/Downloads/course3_Downloads/untitled7.py,第5行df=pd.read_csvrC:\Users\Administrator\Desktop\Csv for PYthon\USDJPY60.Csv,index_col=['Datetime'],parse_dates=['Date','Time']]^SyntaxError:无效syntax@KornTawe-看起来不错,请再次尝试重写代码,因为可能复制了一些坏字符。这显然有帮助。
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