python数据分析--时间序列数据处理

数据来源:和鲸社区-Numpy+Pandas数据处理·第五关-apple股价数据
主要内容:

  • 查看数据类型
  • 日期格式转换
  • 将日期设置为索引
  • 通过索引排序
  • 重采样resample的用法
  • 按照时间序列进行可视化
导入数据
import pandas as pd
import numpy as np

# visualization
import matplotlib.pyplot as plt

%matplotlib inline
filepath9 = "/home/mw/input/Pandas_exercise2020/appl_1980_2014.csv"
apple = pd.read_csv(filepath9)
apple.head()

python数据分析--时间序列数据处理_第1张图片

查看数据类型
# 查看每一列的数据类型
apple.dtypes
日期格式转换
# 将Date这个列转换为datetime类型
apple['Date']=pd.to_datetime(apple['Date'])
apple.info()
#方法一:
#apple['Date'] = apple['Date'].astype('datetime64[ns]')
设置索引
# 将Date设置为索引
apple.set_index('Date',inplace=True)
apple.head()
通过索引进行排序
# # 将index设置为升序
# pandas通过索引进行排序:

# DataFrame.sort_index(ascending=True, inplace = True)
apple.sort_index(ascending=True, inplace=True)
apple.head()
是否有重复日期的判断
apple[apple.index.duplicated()]

python数据分析--时间序列数据处理_第2张图片知识点

#     duplicated()方法判断
#             判断dataframe数据某列是否重复
#                 df.xxx.duplicated()
#             判断dataframe数据整行是否重复
#                 df.duplicated()
#             判断dataframe数据多列数据是否重复(多列组合查)
#                 df.duplicated(subset = ['xxx1','xxx2'])
#     drop_duplicats()方法去重(列)
#         df.drop_duplicats(subset = ['price','cnt'],keep='last',inplace=True)
#     相关资料:
#         https://www.cnblogs.com/trotl/p/11876292.html
重采样
# #  找到每个月的最后一个交易日(business day)
apple_month = apple.resample('BM').mean()
apple_month.head()

python数据分析--时间序列数据处理_第3张图片

#  数据集中最早的日期和最晚的日期相差多少天?
(apple.index.max() - apple.index.min()).days
# 在数据中一共有多少个月?
len(apple_month)
按照时间顺序可视化
# 按照时间顺序可视化Adj Close值
#方法一:
import matplotlib.pyplot as plt
import matplotlib

#设置画图字体格式
font = {'family':'MicroSoft YaHei', 'weight':'bold', 'size': 18}
matplotlib.rc('font', **font)

#设置图片大小和分辨率
plt.figure(figsize=(16, 6), dpi=80)

#绘制折线图
x = apple.index
y1 = apple['Adj Close']
plt.plot(x, y1, label='Adj Close', color='orange', linestyle='-')


#设置x,y轴标签
plt.xlabel("日期")
plt.ylabel("Adj Close")
plt.title("Apple Stock")

#绘制网格
plt.grid(alpha=0.4, linestyle='--')#alpha表示透明度

#添加图例(设置图例时,必须在绘制时,加上label字段,见上plt.plot()函数)
'''upper right;upper left;
   lower left;lower right;
   best; right; center
   center left; center right
   lower center; upper center
'''
plt.legend(loc="upper center")

#展示图
plt.show()

python数据分析--时间序列数据处理_第4张图片

#方法二:
apple['Adj Close'].plot(title = 'Apple Stock').get_figure().set_size_inches(9,5)

python数据分析--时间序列数据处理_第5张图片

resample函数

#     resample函数:
#         用途:频率转换和重新采样时间的便捷方法
#             对象必须具有类似日期时间的索引(DatetimeIndex,PeriodIndex或TimedeltaIndex)
#             或传递datetime值到on或level关键字
#         返回:Resampler object
#     df.resample(rule,how=None,axis=0,fill_method=None,closed=None,label=None,convention=start, kind=None, loffset=None,limit=None, base=0, on=None, level=None)
#         rule:“M”,“A”,“Q”,“BM”,“BA”,“BQ”,和“W”
#             频率转换:
#                 s.resample('3S').asfreq()
#             上采样Upsample:
#                 s.resample('30S').asfreq()[0:5]
#                 s.resample('30S').pad()[0:5] #用前面值填充后面Na
#                 s.resample('30S').bfill()[0:5]#用后面值填充前面Na
#             下采样:
#                 s.resample('2min').asfreq()
#                 对于下采样,closed可以设置为“左”或“右”以指定间隔的哪一端关闭:
#                     s.resample('5Min', closed='left').sum()
#                     s.resample('5Min', closed='right').sum()
#         4.参数:label和loffset
#             参数label和loffset用于处理结果标签。label指定结果是使用间隔的开头还是结尾标记。loffset对输出标签执行时间调整。
#             s.resample('5Min').sum()
#             s.resample('5Min',label='left').sum()
#             s.resample('5Min',label='left',loffset='1s').sum()
#             参数:label和closed
#                 ts2.resample('M',label='right', closed='left').max() #label='right'索引为本月的最后一日即1月31日
#             axis/kind参数:
#                 axis=0或1允许您重新采样指定;kind='timestamp'或'period',将结果索引转换为时间戳/时间范围表示。默认保留输入
#     重采样对象方法:
#         sum,mean,std,sem, max,min,median,first,last,ohlc
#         apply传递自定义函数
#         agg:
#     相关资料:
#         https://blog.csdn.net/tcy23456/article/details/86582835

你可能感兴趣的:(学记笔记,python,数据分析,pandas)