我是 Python 和 Pandas 新手。我编写了一些代码来从 Google Finance 下载 1 分钟的数据。使用以下命令后:
new = pd.read_csv(string, skiprows=7, names = ("d", "o", "h", "l", "c", "v") )
我获得了如下所示的 DataFrame:
d o h l c v 0 a1453905960 95.4500 95.4500 95.0900 95.0980 433810 1 a1453906020 95.0500 95.4700 94.9500 95.4500 934980 2 a1453906080 94.9400 95.1000 94.8700 95.0900 791657 3 a1453906140 94.8990 95.0300 94.7000 94.9620 763531 4 a1453906200 94.9300 95.0300 94.8200 94.8918 501298
其中第一列是 unix 时间戳。
接下来,我使用以下行将 unix 时间戳转换为常规日期时间
new['d']=new['d'].apply(lambda x:datetime.fromtimestamp(int(x[1:])).strftime('%Y-%m-%d %H:%M:%S'))
现在我的 d 列包含带日期的字符串。如果我使用以下几行
new.index = new["d"]
del new["d"]
我只是将旧索引替换为由包含日期时间的字符串组成的新索引。如果我使用以下命令绘制 c 列
new["c"].plot()
如果我使用以下命令将数据帧的索引转换为日期时间对象
new.index = pd.to_datetime(new.index)
然后我尝试
new["c"].plot()
为什么?我有什么误解吗?
提前谢谢您。
最佳答案
第一个 index
来自 string
列 d
,因为 strftime
,第二个是 datetimeindex
也许datetime
不正确,但是datetime.fromtimestamp
对我不起作用。
new['d']= new['d'].apply(lambda x: datetime.date.fromtimestamp(int(x[1:]))
.strftime('%Y-%m-%d %H:%M:%S'))
print new
d o h l c v
0 2016-01-27 00:00:00 95.450 95.45 95.09 95.0980 433810
1 2016-01-27 00:00:00 95.050 95.47 94.95 95.4500 934980
2 2016-01-27 00:00:00 94.940 95.10 94.87 95.0900 791657
3 2016-01-27 00:00:00 94.899 95.03 94.70 94.9620 763531
4 2016-01-27 00:00:00 94.930 95.03 94.82 94.8918 501298
print new.dtypes
d object
o float64
h float64
l float64
c float64
v int64
dtype: object
print type(new.loc[0, 'd'])
<type 'str'>
new.index = new["d"]
del new["d"]
print new.index
Index([u'2016-01-27 00:00:00', u'2016-01-27 00:00:00', u'2016-01-27 00:00:00',
u'2016-01-27 00:00:00', u'2016-01-27 00:00:00'],
dtype='object', name=u'd')
new.index = pd.to_datetime(new.index)
print new.index
DatetimeIndex(['2016-01-27', '2016-01-27', '2016-01-27', '2016-01-27',
'2016-01-27'],
dtype='datetime64[ns]', name=u'd', freq=None)
也许您可以使用 to_datetime
创建列 d
:
new['d'] = pd.to_datetime(new['d'].str[1:].astype(int), unit='s')
或者如果您需要字符串,请使用 strftime
:
new['d'] = pd.to_datetime(new['d'].str[1:].astype(int), unit='s').dt.strftime('%Y-%m-%d %H:%M:%S')
关于python - 当我更改 DataFrame 的索引时,使用 pandas 进行绘图似乎效果不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35465774/