Pandas分类
- categorical data是指分类数据:数据类型为:男女、班级(一班、二班)、省份, 使用赋值法给变量赋值,例如(男=1,女=0),数字1, 0之间没有大小之分,不能认为1是比0大的
- numerical data是指数值型数据:收入(1000元,500元),是可以进行比较大小并进行运算的数据。
从0.15版本开始,pandas可以在DataFrame中支持Categorical类型的数据,
Pandas可以在DataFrame中包含分类数据
df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})
df
df["raw_grade"]
#1 将原始grade成绩转换为分类数据
df["grade"] = df["raw_grade"].astype("category")
df["grade"]
#2.重命名分类数据为更有意义的名称:
df["grade"].cat.categories = ["very good", "good", "very bad"]
df
#3.对类别进行重新排序,增加缺失的类别:
df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"])
df["grade"]
#4.按整理后的类别排序(并非词汇的顺序)
df.sort_values(by="grade")
#5.按类别分组也包括空类别:
df.groupby("grade").size()
Pandas绘图
Pandas的绘图方法封装了Matplotlib的pyplot方法,可以提供简单的绘图功能,对于DataFrame来说,.plot是一种将所有列及其标签进行绘制的简便方法
不常用,实际应用中,一般仍使用Matplotlib绘图
Jupyter notebook中如不显示Pandas绘制图像,解决方法:
- 载入
import Matplotlib.pyplot as plt
,Pandas绘图代码最后加plt.show()
- 或者直接载入IPython魔术命令
%matplotlib inline
,或%pylab inline
(不推荐)(非IPython的py文档载入from pylab import *
)
import numpy as np
import pandas as pd
%matplotlib inline
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()
#plt.show()
在DataFrame中,plot()可以绘制所有带有标签的列
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
df.plot()
#plt.show()
Pandas时间序列
pandas 提供了一组标准的时间序列处理工具和数据算法
数据类型及操作
Python 标准库的 datetime
datetime 模块中的 datetime、 time、 calendar 等类都可以用来存储时间类型以及进行一些转换和运算操作。
from datetime import datetime
now = datetime.now()
now
delta = datetime(2021,4,10)-datetime(2021,4,1)
delta
now + delta
datetime 对象间的减法运算会得到一个 timedelta 对象,表示一个时间段。
datetime 对象与它所保存的字符串格式时间戳之间可以互相转换。str() 函数是可用的,但更推荐 datetime.strptime() 方法。这个方法可以实现双向转换。
str(now)
now.strftime('%Y-%m-%d')
datetime.strptime('2021-04-09','%Y-%m-%d')
pandas 的 TimeStamp
pandas 最基本的时间日期对象是一个从 Series 派生出来的子类 TimeStamp,这个对象与 datetime 对象保有高度兼容性,可通过 pd.to_datetime() 函数转换。(一般是从 datetime 转换为 Timestamp)
pd.to_datetime(now)
pd.to_datetime(np.nan)
pandas 的时间序列
pandas 最基本的时间序列类型就是以时间戳(TimeStamp)为 index 元素的 Series 类型。
dates = [datetime(2021,4,1),datetime(2012,4,2),datetime(2021,4,3)]
ts = pd.Series(np.random.randn(3),index=dates)
ts
type(ts)
ts.index
ts.index[0]
时间序列之间的算术运算会自动按时间对齐。
索引、选取、子集构造
时间序列只是 index 比较特殊的 Series ,因此一般的索引操作对时间序列依然有效。其特别之处在于对时间序列索引的操作优化。如使用各种字符串进行索引:
ts['20210401']
ts['2021-04-09']
ts['01/04/2021']
对于较长的序列,还可以只传入 “年” 或 “年月” 选取切片:
ts
ts['2021']
ts['2021-4-2':'2021-12']
生成日期范围
pd.date_range() 可用于生成指定长度的 DatetimeIndex。参数可以是起始结束日期,或单给一个日期,加一个时间段参数。日期是包含的。
pd.date_range('20210101','20210110')
pd.date_range(start='20210101',periods=10)
pd.date_range(end='20210110',periods=10)
移动(超前和滞后)数据
移动(shifting)指的是沿着时间轴将数据前移或后移。Series 和 DataFrame 都有一个 .shift() 方法用于执行单纯的移动操作,index 维持不变:
ts
ts.shift(2)
ts.shift(-2)
因为移动操作产生了 NA 值,另一种移动方法是移动 index,而保持数据不变。这种移动方法需要额外提供一个 freq 参数来指定移动的频率:
ts.shift(2,freq='D')
ts.shift(2,freq='3D')
时期及其算术运算
时期(period)概念不同于前面的时间戳(timestamp),指的是一个时间段。但在使用上并没有太多不同,pd.Period 类的构造函数仍需要一个时间戳,以及一个 freq 参数。freq 用于指明该 period 的长度,时间戳则说明该 period 在公园时间轴上的位置。
p = pd.Period(2021,freq='M')
p
p + 2
上例中我给 period 的构造器传了一个 “年” 单位的时间戳和一个 “Month” 的 freq,pandas 便自动把 2021 解释为了 2021-01。
period_range 函数可用于创建规则的时间范围:
pd.period_range('2021-01','2021-04',freq='M')
PeriodIndex 类保存了一组 period,它可以在任何 pandas 数据结构中被用作轴索引:
pd.Series(np.random.randn(4),index=pd.period_range('202101','202104',freq='M'))
重采样
Pandas可以通过频率转换简单高效的进行重新采样
Pandas在对频率转换进行重新采样时拥有简单、强大且高效的功能(如将按秒采样的数据转换为按分钟为单位进行采样的数据)。这种操作在金融领域非常常见。
rng = pd.date_range('1/1/2012', periods=100, freq='S')
rng
ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
ts
ts.resample('1Min').sum() #将秒级数据整合(加)成1min的数据
其他类型数值转为时间类型
时间字符串转时间格式:整型例如 20010100000000 这类格式容易当成时间戳转错,带format格式才行
pd.to_datetime(series时间字符,format='%Y%m%d%H%M%S')
a = pd.DataFrame([[20010101,100000,'aaa'],[20010201,230100,'bbb']])
a
pd.to_datetime(a[0],format='%Y%m%d')