Pandas数据分析练习9

练习9-时间序列

探索Apple公司股价数据


步骤1 导入必要的库

运行以下代码

import pandas as pd

import numpy as np

# visualization

import matplotlib.pyplot as plt

%matplotlib inline

步骤2 数据集地址

运行以下代码

#从目标路径导入数据集

path9 = 'D:/hailong/hailong_download/pandas_exercise/exercise_data/Apple_stock.csv'

步骤3 读取数据并存为一个名叫apple的数据框

运行以下代码

apple = pd.read_csv(path9)

apple.head()

输出结果

步骤4 查看每一列的数据类型

运行以下代码

apple.dtypes

输出结果

步骤5 将Date这个列转换为datetime类型

运行以下代码

apple.Date = pd.to_datetime(apple.Date)

apple['Date'].head()

输出结果

步骤6 将Date设置为索引

运行以下代码

apple = apple.set_index('Date')

apple.head()

输出结果

步骤7 有重复的日期吗?

运行以下代码

apple.index.is_unique

输出结果:True

步骤8 将index设置为升序

运行以下代码

apple.sort_index(ascending = True).head()

输出结果

步骤9 找到每个月的最后一个交易日(business day)

运行以下代码

apple_month = apple.resample('BM').mean()

apple_month.head()

输出结果

注意: .resample()在高版本已不再使用(容易出错点)

步骤10 数据集中最早的日期和最晚的日期相差多少天?

运行以下代码

(apple.index.max() - apple.index.min()).days

输出结果:12261

步骤11 在数据中一共有多少个月?

运行以下代码

apple_months = apple.resample('BM').mean()

len(apple_months.index)

输出结果:404

步骤12 按照时间顺序可视化Adj Close值

运行以下代码

# makes the plot and assign it to a variable

apple_open = apple['Adj Close'].plot(title = "Apple stock")

# changes the size of the graph

fig = apple_open.get_figure()

fig.set_size_inches(13.5,9)

输出结果

代码截图

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。