数据分析实例——苹果股票[pd.to_datetime()/set_index()/sort_index()]

一、导包

import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import matplotlib.pyplot as plt

二、读取数据

app = pd.read_csv('./AAPL.csv')
app.shape
Out:  (9385, 7)

app.head()

三、检查数据类型

# Date str类型数据
app.dtypes
Out:
Date          object
Open         float64
High         float64
Low          float64
Close        float64
Adj Close    float64
Volume       float64
dtype: object

四、将'Date'这行数据转换为时间数据类型:pd.to_datetime()

app['Date'] = pd.to_datetime(app['Date'])
app.head()

五、查看数据类型

app.dtypes
Out:
Date         datetime64[ns]
Open                float64
High                float64
Low                 float64
Close               float64
Adj Close           float64
Volume              float64
dtype: object

六、将'Date'设置为行索引并按时间排序:set_index()/sort_index()

app.set_index('Date',inplace=True)
# 时间,先后
# 排序
app.sort_index()
app.head()

七、绘制图形,字段Adj Close:已调整收盘价格

# pandas 绘图,依赖于matplotlib
plot = app['Adj Close'].plot()

# 获取图片
fig = plot.get_figure()

# 设置图片的尺寸
fig.set_size_inches(12,9)

若不改变时间的数据类型:

appl = pd.read_csv('./AAPL.csv')

appl.set_index('Date',inplace=True)
appl.head()

appl['Adj Close'].plot()

猜你喜欢

转载自blog.csdn.net/Dorisi_H_n_q/article/details/82413916