当我通过他们的API查询服务的日常数据时,他们会投入一个时间部分,该时间部分等于查询的时间.所以当我在14:54:36调用函数时,我的pandas数据框看起来像这样 -
2018-05-16 14:54:36 1024.75 1008.25 ... 39221 242897
2018-05-17 14:54:36 1017.00 1002.00 ... 35361 241132
2018-05-18 14:54:36 1015.75 1002.75 ... 49090 242938
2018-05-21 14:54:36 1034.50 1020.75 ... 56950 243316
2018-05-22 14:54:36 1043.75 1028.50 ... 49724 247874
2018-05-23 14:54:36 1049.00 1036.25 ... 46256 253609
2018-05-24 14:54:36 1059.75 1047.00 ... 65352 259617
Run Code Online (Sandbox Code Playgroud)
由于这是每日数据,因此时间部分无用.当我做:
data = pd.read_csv(StringIO(data), index_col=0, header=None,names=['High','Low','Open','Close','Volume','OpenInterest'])
data.index = pd.to_datetime(data.index,format="%Y-%m-%d")
Run Code Online (Sandbox Code Playgroud)
格式似乎不起作用.DateTime索引仍包含时间.知道如何删除时间部分吗?
使用date属性:
df.index = df.index.date
Run Code Online (Sandbox Code Playgroud)
例:
>>> df = pd.DataFrame([1, 2, 3, 4], index=pd.date_range('2018', periods=4, freq='H'))
>>> df.index = df.index.date
>>> df
0
2018-01-01 1
2018-01-01 2
2018-01-01 3
2018-01-01 4
Run Code Online (Sandbox Code Playgroud)
请注意,这将使您object在Pandas中获得dtype.所有属性都在这里.
还可以选择保留日期时间功能,但只需将时间部分设置为00:00:00
df.index = df.index.normalize()
Run Code Online (Sandbox Code Playgroud)
import pandas as pd
df = pd.DataFrame([1, 2, 3, 4], index=pd.date_range('2018', periods=4, freq='H'))
df.index = df.index.normalize()
Run Code Online (Sandbox Code Playgroud)
df 就是现在:
0
2018-01-01 1
2018-01-01 2
2018-01-01 3
2018-01-01 4
Run Code Online (Sandbox Code Playgroud)
看一下索引:
df.index
#DatetimeIndex(['2018-01-01', '2018-01-01', '2018-01-01', '2018-01-01'], dtype='datetime64[ns]', freq=None)
Run Code Online (Sandbox Code Playgroud)
值是时间戳:
df.index[0]
#Timestamp('2018-01-01 00:00:00')
Run Code Online (Sandbox Code Playgroud)