come from : https://www.cnblogs.com/prpl/p/5537417.html
一、常用链接:
1.Python官网:https://www.python.org/
2.各种库的whl离线安装包:http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn
3.数据分析常用库的离线安装包(pip+wheels)(百度云):http://pan.baidu.com/s/1dEMXbfN 密码:bbs2
二、常用库
1.NumPy
NumPy是高性能科学计算和数据分析的基础包。部分功能如下:
-
- ndarray, 具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组。
- 用于对整组数据进行快速运算的标准数学函数(无需编写循环)。
- 用于读写磁盘数据的工具以及用于操作内存映射文件的工具。
- 线性代数、随机数生成以及傅里叶变换功能。
- 用于集成C、C++、Fortran等语言编写的代码的工具。
首先要导入numpy库:import numpy as np
A NumPy函数和属性:
类型 | 类型代码 | 说明 |
int8、uint8 | i1、u1 | 有符号和无符号8位整型(1字节) |
int16、uint16 | i2、u2 | 有符号和无符号16位整型(2字节) |
int32、uint32 | i4、u4 | 有符号和无符号32位整型(4字节) |
int64、uint64 | i8、u8 | 有符号和无符号64位整型(8字节) |
float16 | f2 | 半精度浮点数 |
float32 | f4、f | 单精度浮点数 |
float64 | f8、d | 双精度浮点数 |
float128 | f16、g | 扩展精度浮点数 |
complex64 | c8 | 分别用两个32位表示的复数 |
complex128 | c16 | 分别用两个64位表示的复数 |
complex256 | c32 | 分别用两个128位表示的复数 |
bool | ? | 布尔型 |
object | O | python对象 |
string | Sn | 固定长度字符串,每个字符1字节,如S10 |
unicode | Un | 固定长度Unicode,字节数由系统决定,如U10 |
表2.1.A.1 NumPy类型
生成函数 | 作用 |
np.array( x) np.array( x, dtype) | 将输入数据转化为一个ndarray 将输入数据转化为一个类型为type的ndarray |
np.asarray( array ) | 将输入数据转化为一个新的(copy)ndarray |
np.ones( N ) np.ones( N, dtype) np.ones_like( ndarray ) | 生成一个N长度的一维全一ndarray 生成一个N长度类型是dtype的一维全一ndarray 生成一个形状与参数相同的全一ndarray |
np.zeros( N) np.zeros( N, dtype) np.zeros_like(ndarray) | 生成一个N长度的一维全零ndarray 生成一个N长度类型位dtype的一维全零ndarray 类似np.ones_like( ndarray ) |
np.empty( N ) np.empty( N, dtype) np.empty(ndarray) | 生成一个N长度的未初始化一维ndarray 生成一个N长度类型是dtype的未初始化一维ndarray 类似np.ones_like( ndarray ) |
np.eye( N ) np.identity( N ) | 创建一个N * N的单位矩阵(对角线为1,其余为0) |
np.arange( num) np.arange( begin, end) np.arange( begin, end, step) | 生成一个从0到num-1步数为1的一维ndarray 生成一个从begin到end-1步数为1的一维ndarray 生成一个从begin到end-step的步数为step的一维ndarray |
np.mershgrid(ndarray, ndarray,...) | 生成一个ndarray * ndarray * ...的多维ndarray |
np.where(cond, ndarray1, ndarray2) | 根据条件cond,选取ndarray1或者ndarray2,返回一个新的ndarray |
np.in1d(ndarray, [x,y,...]) | 检查ndarray中的元素是否等于[x,y,...]中的一个,返回bool数组 |
矩阵函数 | 说明 |
np.diag( ndarray) np.diag( [x,y,...]) | 以一维数组的形式返回方阵的对角线(或非对角线)元素 将一维数组转化为方阵(非对角线元素为0) |
np.dot(ndarray, ndarray) | 矩阵乘法 |
np.trace( ndarray) | 计算对角线元素的和 |
排序函数 | 说明 |
np.sort( ndarray) | 排序,返回副本 |
np.unique(ndarray) | 返回ndarray中的元素,排除重复元素之后,并进行排序 |
np.intersect1d( ndarray1, ndarray2) np.union1d( ndarray1, ndarray2) np.setdiff1d( ndarray1, ndarray2) np.setxor1d( ndarray1, ndarray2) | 返回二者的交集并排序。 返回二者的并集并排序。 返回二者的差。 返回二者的对称差 |
一元计算函数 | 说明 |
np.abs(ndarray) np.fabs(ndarray) | 计算绝对值 计算绝对值(非复数) |
np.mean(ndarray) | 求平均值 |
np.sqrt(ndarray) | 计算x^0.5 |
np.square(ndarray) | 计算x^2 |
np.exp(ndarray) | 计算e^x |
log、log10、log2、log1p | 计算自然对数、底为10的log、底为2的log、底为(1+x)的log |
np.sign(ndarray) | 计算正负号:1(正)、0(0)、-1(负) |
np.ceil(ndarray) np.floor(ndarray) np.rint(ndarray) | 计算大于等于改值的最小整数 计算小于等于该值的最大整数 四舍五入到最近的整数,保留dtype |
np.modf(ndarray) | 将数组的小数和整数部分以两个独立的数组方式返回 |
np.isnan(ndarray) | 返回一个判断是否是NaN的bool型数组 |
np.isfinite(ndarray) np.isinf(ndarray) | 返回一个判断是否是有穷(非inf,非NaN)的bool型数组 返回一个判断是否是无穷的bool型数组 |
cos、cosh、sin、sinh、tan、tanh | 普通型和双曲型三角函数 |
arccos、arccosh、arcsin、arcsinh、arctan、arctanh | 反三角函数和双曲型反三角函数 |
np.logical_not(ndarray) | 计算各元素not x的真值,相当于-ndarray |
多元计算函数 | 说明 |
np.add(ndarray, ndarray) np.subtract(ndarray, ndarray) np.multiply(ndarray, ndarray) np.divide(ndarray, ndarray) np.floor_divide(ndarray, ndarray) np.power(ndarray, ndarray) np.mod(ndarray, ndarray) | 相加 相减 乘法 除法 圆整除法(丢弃余数) 次方 求模 |
np.maximum(ndarray, ndarray) np.fmax(ndarray, ndarray) np.minimun(ndarray, ndarray) np.fmin(ndarray, ndarray) | 求最大值 求最大值(忽略NaN) 求最小值 求最小值(忽略NaN) |
np.copysign(ndarray, ndarray) | 将参数2中的符号赋予参数1 |
np.greater(ndarray, ndarray) np.greater_equal(ndarray, ndarray) np.less(ndarray, ndarray) np.less_equal(ndarray, ndarray) np.equal(ndarray, ndarray) np.not_equal(ndarray, ndarray) | > >= < <= == != |
logical_and(ndarray, ndarray) logical_or(ndarray, ndarray) logical_xor(ndarray, ndarray) | & | ^ |
np.dot( ndarray, ndarray) | 计算两个ndarray的矩阵内积 |
np.ix_([x,y,m,n],...) | 生成一个索引器,用于Fancy indexing(花式索引) |
文件读写 | 说明 |
np.save(string, ndarray) | 将ndarray保存到文件名为 [string].npy 的文件中(无压缩) |
np.savez(string, ndarray1, ndarray2, ...) | 将所有的ndarray压缩保存到文件名为[string].npy的文件中 |
np.savetxt(sring, ndarray, fmt, newline='\n') | 将ndarray写入文件,格式为fmt |
np.load(string) | 读取文件名string的文件内容并转化为ndarray对象(或字典对象) |
np.loadtxt(string, delimiter) | 读取文件名string的文件内容,以delimiter为分隔符转化为ndarray |
表2.1.A.2 np常用函数
B NumPy.ndarray函数和属性:
ndarray.ndim | 获取ndarray的维数 |
ndarray.shape | 获取ndarray各个维度的长度 |
ndarray.dtype | 获取ndarray中元素的数据类型 |
ndarray.T | 简单转置矩阵ndarray |
表2.1.B.1 ndarray属性
函数 | 说明 |
ndarray.astype(dtype) | 转换类型,若转换失败则会出现TypeError |
ndarray.copy() | 复制一份ndarray(新的内存空间) |
ndarray.reshape((N,M,...)) | 将ndarray转化为N*M*...的多维ndarray(非copy) |
ndarray.transpose((xIndex,yIndex,...)) | 根据维索引xIndex,yIndex...进行矩阵转置,依赖于shape,不能用于一维矩阵(非copy) |
ndarray.swapaxes(xIndex,yIndex) | 交换维度(非copy) |
计算函数 | 说明 |
ndarray.mean( axis=0 ) | 求平均值 |
ndarray.sum( axis= 0) | 求和 |
ndarray.cumsum( axis=0) ndarray.cumprod( axis=0) | 累加 累乘 |
ndarray.std() ndarray.var() | 方差 标准差 |
ndarray.max() ndarray.min() | 最大值 最小值 |
ndarray.argmax() ndarray.argmin() | 最大值索引 最小值索引 |
ndarray.any() ndarray.all() | 是否至少有一个True 是否全部为True |
ndarray.dot( ndarray) | 计算矩阵内积 |
排序函数 | 说明 |
ndarray.sort(axis=0) | 排序,返回源数据 |
表2.1.B.2 ndarray函数
ndarray[n] | 选取第n+1个元素 |
ndarray[n:m] | 选取第n+1到第m个元素 |
ndarray[:] | 选取全部元素 |
ndarray[n:] | 选取第n+1到最后一个元素 |
ndarray[:n] | 选取第0到第n个元素 |
ndarray[ bool_ndarray ] 注:bool_ndarray表示bool类型的ndarray | 选取为true的元素 |
ndarray[[x,y,m,n]]... | 选取顺序和序列为x、y、m、n的ndarray |
ndarray[n,m] ndarray[n][m] | 选取第n+1行第m+1个元素 |
ndarray[n,m,...] ndarray[n][m].... | 选取n行n列....的元素 |
表2.1.B.3 ndarray索引/切片方式
C NumPy.random函数和属性:
函数 | 说明 |
seed() seed(int) seed(ndarray) | 确定随机数生成种子 |
permutation(int) permutation(ndarray) | 返回一个一维从0~9的序列的随机排列 返回一个序列的随机排列 |
shuffle(ndarray) | 对一个序列就地随机排列 |
rand(int) randint(begin,end,num=1) | 产生int个均匀分布的样本值 从给定的begin和end随机选取num个整数 |
randn(N, M, ...) | 生成一个N*M*...的正态分布(平均值为0,标准差为1)的ndarray |
normal(size=(N,M,...)) | 生成一个N*M*...的正态(高斯)分布的ndarray |
beta(ndarray1,ndarray2) | 产生beta分布的样本值,参数必须大于0 |
chisquare() | 产生卡方分布的样本值 |
gamma() | 产生gamma分布的样本值 |
uniform() | 产生在[0,1)中均匀分布的样本值 |
2.1.C.1 random常用函数
D NumPy.linalg函数和属性:
函数 | 说明 |
det(ndarray) | 计算矩阵列式 |
eig(ndarray) | 计算方阵的本征值和本征向量 |
inv(ndarray) pinv(ndarray) | 计算方阵的逆 计算方阵的Moore-Penrose伪逆 |
qr(ndarray) | 计算qr分解 |
svd(ndarray) | 计算奇异值分解svd |
solve(ndarray) | 解线性方程组Ax = b,其中A为方阵 |
lstsq(ndarray) | 计算Ax=b的最小二乘解 |
2.1.D.1 linalg常用函数
2.Pandas
pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。pandas提供了大量能使我们快速便捷地处理数据的函数和方法。
>>> from pandas import Series, DataFrame
>>> import pandas as pd
A.pandas
函数 | 说明 |
pd.isnull(series) pd.notnull(series) | 判断是否为空(NaN) 判断是否不为空(not NaN) |
2.2.A.1 pandas常用函数
B.Series
Series可以运用ndarray或字典的几乎所有索引操作和函数,融合了字典和ndarray的优点。
属性 | 说明 |
values | 获取数组 |
index | 获取索引 |
name | values的name |
index.name | 索引的name |
2.2.B.1 Series常用属性
函数 | 说明 |
Series([x,y,...])Series({'a':x,'b':y,...}, index=param1) | 生成一个Series |
Series.copy() | 复制一个Series |
Series.reindex([x,y,...], fill_value=NaN) Series.reindex([x,y,...], method=NaN) Series.reindex(columns=[x,y,...]) | 重返回一个适应新索引的新对象,将缺失值填充为fill_value 返回适应新索引的新对象,填充方式为method 对列进行重新索引 |
Series.drop(index) | 丢弃指定项 |
Series.map(f) | 应用元素级函数 |
排序函数 | 说明 |
Series.sort_index(ascending=True) | 根据索引返回已排序的新对象 |
Series.order(ascending=True) | 根据值返回已排序的对象,NaN值在末尾 |
Series.rank(method='average', ascending=True, axis=0) | 为各组分配一个平均排名 |
df.argmax() df.argmin() | 返回含有最大值的索引位置 返回含有最小值的索引位置 |
2.2.B.2 Series常用函数
reindex的method选项:
ffill, bfill 向前填充/向后填充
pad, backfill 向前搬运,向后搬运
rank的method选项
'average' 在相等分组中,为各个值分配平均排名
'max','min' 使用整个分组中的最小排名
'first' 按值在原始数据中出现的顺序排名
C.DataFrame
DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔值等)。DataFrame既有行索引也有列索引,它可以被看做由Series组成的字典(共用同一个索引)。
DataFrame可以通过类似字典的方式或者.columnname的方式将列获取为一个Series。行也可以通过位置或名称的方式进行获取。
为不存在的列赋值会创建新列。
>>> del frame['xxx'] # 删除列
属性 | 说明 |
values | DataFrame的值 |
index | 行索引 |
index.name | 行索引的名字 |
columns | 列索引 |
columns.name | 列索引的名字 |
ix | 返回行的DataFrame |
ix[[x,y,...], [x,y,...]] | 对行重新索引,然后对列重新索引 |
T | frame行列转置 |
2.2.C.1 DataFrame常用属性
函数 | 说明 |
DataFrame(dict, columns=dict.index, index=[dict.columnnum]) DataFrame(二维ndarray) DataFrame(由数组、列表或元组组成的字典) DataFrame(NumPy的结构化/记录数组) DataFrame(由Series组成的字典) DataFrame(由字典组成的字典) DataFrame(字典或Series的列表) DataFrame(由列表或元组组成的列表) DataFrame(DataFrame) DataFrame(NumPy的MaskedArray) | 构建DataFrame 数据矩阵,还可以传入行标和列标 每个序列会变成DataFrame的一列。所有序列的长度必须相同 类似于“由数组组成的字典” 每个Series会成为一列。如果没有显式制定索引,则各Series的索引会被合并成结果的行索引 各内层字典会成为一列。键会被合并成结果的行索引。 各项将会成为DataFrame的一行。索引的并集会成为DataFrame的列标。 类似于二维ndarray 沿用DataFrame 类似于二维ndarray,但掩码结果会变成NA/缺失值
|
df.reindex([x,y,...], fill_value=NaN, limit) df.reindex([x,y,...], method=NaN) df.reindex([x,y,...], columns=[x,y,...],copy=True) | 返回一个适应新索引的新对象,将缺失值填充为fill_value,最大填充量为limit 返回适应新索引的新对象,填充方式为method 同时对行和列进行重新索引,默认复制新对象。 |
df.drop(index, axis=0) | 丢弃指定轴上的指定项。 |
排序函数 | 说明 |
df.sort_index(axis=0, ascending=True) df.sort_index(by=[a,b,...]) | 根据索引排序 |
汇总统计函数 | 说明 |
df.count() | 非NaN的数量 |
df.describe() | 一次性产生多个汇总统计 |
df.min() df.min() | 最小值 最大值 |
df.idxmax(axis=0, skipna=True) df.idxmin(axis=0, skipna=True) | 返回含有最大值的index的Series 返回含有最小值的index的Series |
df.quantile(axis=0) | 计算样本的分位数 |
df.sum(axis=0, skipna=True, level=NaN) df.mean(axis=0, skipna=True, level=NaN) df.median(axis=0, skipna=True, level=NaN) df.mad(axis=0, skipna=True, level=NaN) df.var(axis=0, skipna=True, level=NaN) df.std(axis=0, skipna=True, level=NaN) df.skew(axis=0, skipna=True, level=NaN) df.kurt(axis=0, skipna=True, level=NaN) df.cumsum(axis=0, skipna=True, level=NaN) df.cummin(axis=0, skipna=True, level=NaN) df.cummax(axis=0, skipna=True, level=NaN) df.cumprod(axis=0, skipna=True, level=NaN) df.diff(axis=0) df.pct_change(axis=0) | 返回一个含有求和小计的Series 返回一个含有平均值的Series 返回一个含有算术中位数的Series 返回一个根据平均值计算平均绝对离差的Series 返回一个方差的Series 返回一个标准差的Series 返回样本值的偏度(三阶距) 返回样本值的峰度(四阶距) 返回样本的累计和 返回样本的累计最大值 返回样本的累计最小值 返回样本的累计积 返回样本的一阶差分 返回样本的百分比数变化 |
计算函数 | 说明 |
df.add(df2, fill_value=NaN, axist=1) df.sub(df2, fill_value=NaN, axist=1) df.div(df2, fill_value=NaN, axist=1) df.mul(df2, fill_value=NaN, axist=1) | 元素级相加,对齐时找不到元素默认用fill_value 元素级相减,对齐时找不到元素默认用fill_value 元素级相除,对齐时找不到元素默认用fill_value 元素级相乘,对齐时找不到元素默认用fill_value |
df.apply(f, axis=0) | 将f函数应用到由各行各列所形成的一维数组上 |
df.applymap(f) | 将f函数应用到各个元素上 |
df.cumsum(axis=0, skipna=True) | 累加,返回累加后的dataframe |
2.2.C.2 Dataframe常用函数
索引方式 | 说明 |
df[val] | 选取DataFrame的单个列或一组列 |
df.ix[val] | 选取Dataframe的单个行或一组行 |
df.ix[:,val] | 选取单个列或列子集 |
df.ix[val1,val2] | 将一个或多个轴匹配到新索引 |
reindex方法 | 将一个或多个轴匹配到新索引 |
xs方法 | 根据标签选取单行或者单列,返回一个Series |
icol、irow方法 | 根据整数位置选取单列或单行,并返回一个Series |
get_value、set_value | 根据行标签和列标签选取单个值 |
2.2.C.3 Dataframe常用索引方式
运算:
默认情况下,Dataframe和Series之间的算术运算会将Series的索引匹配到的Dataframe的列,沿着列一直向下传播。若索引找不到,则会重新索引产生并集。
D.Index
pandas的索引对象负责管理轴标签和其他元数据(比如轴名称等)。构建Series或DataFrame时,所用到的任何数组或其他序列的标签都会被转换成一个Index。Index对象不可修改,从而在多个数据结构之间安全共享。
主要的Index对象 | 说明 |
Index | 最广泛的Index对象,将轴标签表示为一个由Python对象组成的NumPy数组 |
Int64Index | 针对整数的特殊Index |
MultiIndex | “层次化”索引对象,表示单个轴上的多层索引。可以看做由元组组成的数组 |
DatetimeIndex | 存储纳秒级时间戳(用NumPy的Datetime64类型表示) |
PeriodIndex | 针对Period数据(时间间隔)的特殊Index |
2.2.D.1 主要的Index属性
函数 | 说明 |
Index([x,y,...]) | 创建索引 |
append(Index) | 连接另一个Index对象,产生一个新的Index |
diff(Index) | 计算差集,产生一个新的Index |
intersection(Index) | 计算交集 |
union(Index) | 计算并集 |
isin(Index) | 检查是否存在与参数索引中,返回bool型数组 |
delete(i) | 删除索引i处元素,得到新的Index |
drop(str) | 删除传入的值,得到新Index |
insert(i,str) | 将元素插入到索引i处,得到新Index |
is_monotonic() | 当各元素大于前一个元素时,返回true |
is_unique() | 当Index没有重复值时,返回true |
unique() | 计算Index中唯一值的数组 |
2.2.D.2 常用Index函数
and come from : http://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html
10 Minutes to pandas
This is a short introduction to pandas, geared mainly for new users. You can see more complex recipes in the Cookbook.
Customarily, we import as follows:
In [1]: import numpy as np
In [2]: import pandas as pd
Object Creation
See the Data Structure Intro section.
Creating a Series
by passing a list of values, letting pandas create a default integer index:
In [3]: s = pd.Series([1, 3, 5, np.nan, 6, 8])
In [4]: s
Out[4]:
0 1.0
1 3.0
2 5.0
3 NaN
4 6.0
5 8.0
dtype: float64
Creating a DataFrame
by passing a NumPy array, with a datetime index and labeled columns:
In [5]: dates = pd.date_range('20130101', periods=6)
In [6]: dates
Out[6]:
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
'2013-01-05', '2013-01-06'],
dtype='datetime64[ns]', freq='D')
In [7]: df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
In [8]: df
Out[8]:
A B C D
2013-01-01 0.469112 -0.282863 -1.509059 -1.135632
2013-01-02 1.212112 -0.173215 0.119209 -1.044236
2013-01-03 -0.861849 -2.104569 -0.494929 1.071804
2013-01-04 0.721555 -0.706771 -1.039575 0.271860
2013-01-05 -0.424972 0.567020 0.276232 -1.087401
2013-01-06 -0.673690 0.113648 -1.478427 0.524988
Creating a DataFrame
by passing a dict of objects that can be converted to series-like.
In [9]: df2 = pd.DataFrame({'A': 1.,
...: 'B': pd.Timestamp('20130102'),
...: 'C': pd.Series(1, index=list(range(4)), dtype='float32'),
...: 'D': np.array([3] * 4, dtype='int32'),
...: 'E': pd.Categorical(["test", "train", "test", "train"]),
...: 'F': 'foo'})
...:
In [10]: df2
Out[10]:
A B C D E F
0 1.0 2013-01-02 1.0 3 test foo
1 1.0 2013-01-02 1.0 3 train foo
2 1.0 2013-01-02 1.0 3 test foo
3 1.0 2013-01-02 1.0 3 train foo
The columns of the resulting DataFrame
have different dtypes.
In [11]: df2.dtypes
Out[11]:
A float64
B datetime64[ns]
C float32
D int32
E category
F object
dtype: object
If you’re using IPython, tab completion for column names (as well as public attributes) is automatically enabled. Here’s a subset of the attributes that will be completed:
In [12]: df2.<TAB> # noqa: E225, E999
df2.A df2.bool
df2.abs df2.boxplot
df2.add df2.C
df2.add_prefix df2.clip
df2.add_suffix df2.clip_lower
df2.align df2.clip_upper
df2.all df2.columns
df2.any df2.combine
df2.append df2.combine_first
df2.apply df2.compound
df2.applymap df2.consolidate
df2.D
As you can see, the columns A
, B
, C
, and D
are automatically tab completed. E
is there as well; the rest of the attributes have been truncated for brevity.
Viewing Data
See the Basics section.
Here is how to view the top and bottom rows of the frame:
In [13]: df.head()
Out[13]:
A B C D
2013-01-01 0.469112 -0.282863 -1.509059 -1.135632
2013-01-02 1.212112 -0.173215 0.119209 -1.044236
2013-01-03 -0.861849 -2.104569 -0.494929 1.071804
2013-01-04 0.721555 -0.706771 -1.039575 0.271860
2013-01-05 -0.424972 0.567020 0.276232 -1.087401
In [14]: df.tail(3)
Out[14]:
A B C D
2013-01-04 0.721555 -0.706771 -1.039575 0.271860
2013-01-05 -0.424972 0.567020 0.276232 -1.087401
2013-01-06 -0.673690 0.113648 -1.478427 0.524988
Display the index, columns:
In [15]: df.index
Out[15]:
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
'2013-01-05', '2013-01-06'],
dtype='datetime64[ns]', freq='D')
In [16]: df.columns
Out[16]: Index(['A', 'B', 'C', 'D'], dtype='object')
DataFrame.to_numpy()
gives a NumPy representation of the underlying data. Note that his can be an expensive operation when your DataFrame
has columns with different data types, which comes down to a fundamental difference between pandas and NumPy: NumPy arrays have one dtype for the entire array, while pandas DataFrames have one dtype per column. When you call DataFrame.to_numpy()
, pandas will find the NumPy dtype that can hold allof the dtypes in the DataFrame. This may end up being object
, which requires casting every value to a Python object.
For df
, our DataFrame
of all floating-point values, DataFrame.to_numpy()
is fast and doesn’t require copying data.
In [17]: df.to_numpy()
Out[17]:
array([[ 0.4691, -0.2829, -1.5091, -1.1356],
[ 1.2121, -0.1732, 0.1192, -1.0442],
[-0.8618, -2.1046, -0.4949, 1.0718],
[ 0.7216, -0.7068, -1.0396, 0.2719],
[-0.425 , 0.567 , 0.2762, -1.0874],
[-0.6737, 0.1136, -1.4784, 0.525 ]])
For df2
, the DataFrame
with multiple dtypes, DataFrame.to_numpy()
is relatively expensive.
In [18]: df2.to_numpy()
Out[18]:
array([[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo'],
[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo']], dtype=object)
Note
DataFrame.to_numpy()
does not include the index or column labels in the output.
describe()
shows a quick statistic summary of your data:
In [19]: df.describe()
Out[19]:
A B C D
count 6.000000 6.000000 6.000000 6.000000
mean 0.073711 -0.431125 -0.687758 -0.233103
std 0.843157 0.922818 0.779887 0.973118
min -0.861849 -2.104569 -1.509059 -1.135632
25% -0.611510 -0.600794 -1.368714 -1.076610
50% 0.022070 -0.228039 -0.767252 -0.386188
75% 0.658444 0.041933 -0.034326 0.461706
max 1.212112 0.567020 0.276232 1.071804
Transposing your data:
In [20]: df.T
Out[20]:
2013-01-01 2013-01-02 2013-01-03 2013-01-04 2013-01-05 2013-01-06
A 0.469112 1.212112 -0.861849 0.721555 -0.424972 -0.673690
B -0.282863 -0.173215 -2.104569 -0.706771 0.567020 0.113648
C -1.509059 0.119209 -0.494929 -1.039575 0.276232 -1.478427
D -1.135632 -1.044236 1.071804 0.271860 -1.087401 0.524988
Sorting by an axis:
In [21]: df.sort_index(axis=1, ascending=False)
Out[21]:
D C B A
2013-01-01 -1.135632 -1.509059 -0.282863 0.469112
2013-01-02 -1.044236 0.119209 -0.173215 1.212112
2013-01-03 1.071804 -0.494929 -2.104569 -0.861849
2013-01-04 0.271860 -1.039575 -0.706771 0.721555
2013-01-05 -1.087401 0.276232 0.567020 -0.424972
2013-01-06 0.524988 -1.478427 0.113648 -0.673690
Sorting by values:
In [22]: df.sort_values(by='B')
Out[22]:
A B C D
2013-01-03 -0.861849 -2.104569 -0.494929 1.071804
2013-01-04 0.721555 -0.706771 -1.039575 0.271860
2013-01-01 0.469112 -0.282863 -1.509059 -1.135632
2013-01-02 1.212112 -0.173215 0.119209 -1.044236
2013-01-06 -0.673690 0.113648 -1.478427 0.524988
2013-01-05 -0.424972 0.567020 0.276232 -1.087401
Selection
Note
While standard Python / Numpy expressions for selecting and setting are intuitive and come in handy for interactive work, for production code, we recommend the optimized pandas data access methods, .at
, .iat
, .loc
and .iloc
.
See the indexing documentation Indexing and Selecting Data and MultiIndex / Advanced Indexing.
Getting
Selecting a single column, which yields a Series
, equivalent to df.A
:
In [23]: df['A']
Out[23]:
2013-01-01 0.469112
2013-01-02 1.212112
2013-01-03 -0.861849
2013-01-04 0.721555
2013-01-05 -0.424972
2013-01-06 -0.673690
Freq: D, Name: A, dtype: float64
Selecting via []
, which slices the rows.
In [24]: df[0:3]
Out[24]:
A B C D
2013-01-01 0.469112 -0.282863 -1.509059 -1.135632
2013-01-02 1.212112 -0.173215 0.119209 -1.044236
2013-01-03 -0.861849 -2.104569 -0.494929 1.071804
In [25]: df['20130102':'20130104']
Out[25]:
A B C D
2013-01-02 1.212112 -0.173215 0.119209 -1.044236
2013-01-03 -0.861849 -2.104569 -0.494929 1.071804
2013-01-04 0.721555 -0.706771 -1.039575 0.271860
Selection by Label
See more in Selection by Label.
For getting a cross section using a label:
In [26]: df.loc[dates[0]]
Out[26]:
A 0.469112
B -0.282863
C -1.509059
D -1.135632
Name: 2013-01-01 00:00:00, dtype: float64
Selecting on a multi-axis by label:
In [27]: df.loc[:, ['A', 'B']]
Out[27]:
A B
2013-01-01 0.469112 -0.282863
2013-01-02 1.212112 -0.173215
2013-01-03 -0.861849 -2.104569
2013-01-04 0.721555 -0.706771
2013-01-05 -0.424972 0.567020
2013-01-06 -0.673690 0.113648
Showing label slicing, both endpoints are included:
In [28]: df.loc['20130102':'20130104', ['A', 'B']]
Out[28]:
A B
2013-01-02 1.212112 -0.173215
2013-01-03 -0.861849 -2.104569
2013-01-04 0.721555 -0.706771
Reduction in the dimensions of the returned object:
In [29]: df.loc['20130102', ['A', 'B']]
Out[29]:
A 1.212112
B -0.173215
Name: 2013-01-02 00:00:00, dtype: float64
For getting a scalar value:
In [30]: df.loc[dates[0], 'A']
Out[30]: 0.46911229990718628
For getting fast access to a scalar (equivalent to the prior method):
In [31]: df.at[dates[0], 'A']
Out[31]: 0.46911229990718628
Selection by Position
See more in Selection by Position.
Select via the position of the passed integers:
In [32]: df.iloc[3]
Out[32]:
A 0.721555
B -0.706771
C -1.039575
D 0.271860
Name: 2013-01-04 00:00:00, dtype: float64
By integer slices, acting similar to numpy/python:
In [33]: df.iloc[3:5, 0:2]
Out[33]:
A B
2013-01-04 0.721555 -0.706771
2013-01-05 -0.424972 0.567020
By lists of integer position locations, similar to the numpy/python style:
In [34]: df.iloc[[1, 2, 4], [0, 2]]
Out[34]:
A C
2013-01-02 1.212112 0.119209
2013-01-03 -0.861849 -0.494929
2013-01-05 -0.424972 0.276232
For slicing rows explicitly:
In [35]: df.iloc[1:3, :]
Out[35]:
A B C D
2013-01-02 1.212112 -0.173215 0.119209 -1.044236
2013-01-03 -0.861849 -2.104569 -0.494929 1.071804
For slicing columns explicitly:
In [36]: df.iloc[:, 1:3]
Out[36]:
B C
2013-01-01 -0.282863 -1.509059
2013-01-02 -0.173215 0.119209
2013-01-03 -2.104569 -0.494929
2013-01-04 -0.706771 -1.039575
2013-01-05 0.567020 0.276232
2013-01-06 0.113648 -1.478427
For getting a value explicitly:
In [37]: df.iloc[1, 1]
Out[37]: -0.17321464905330858
For getting fast access to a scalar (equivalent to the prior method):
In [38]: df.iat[1, 1]
Out[38]: -0.17321464905330858
Boolean Indexing
Using a single column’s values to select data.
In [39]: df[df.A > 0]
Out[39]:
A B C D
2013-01-01 0.469112 -0.282863 -1.509059 -1.135632
2013-01-02 1.212112 -0.173215 0.119209 -1.044236
2013-01-04 0.721555 -0.706771 -1.039575 0.271860
Selecting values from a DataFrame where a boolean condition is met.
In [40]: df[df > 0]
Out[40]:
A B C D
2013-01-01 0.469112 NaN NaN NaN
2013-01-02 1.212112 NaN 0.119209 NaN
2013-01-03 NaN NaN NaN 1.071804
2013-01-04 0.721555 NaN NaN 0.271860
2013-01-05 NaN 0.567020 0.276232 NaN
2013-01-06 NaN 0.113648 NaN 0.524988
Using the isin()
method for filtering:
In [41]: df2 = df.copy()
In [42]: df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three']
In [43]: df2
Out[43]:
A B C D E
2013-01-01 0.469112 -0.282863 -1.509059 -1.135632 one
2013-01-02 1.212112 -0.173215 0.119209 -1.044236 one
2013-01-03 -0.861849 -2.104569 -0.494929 1.071804 two
2013-01-04 0.721555 -0.706771 -1.039575 0.271860 three
2013-01-05 -0.424972 0.567020 0.276232 -1.087401 four
2013-01-06 -0.673690 0.113648 -1.478427 0.524988 three
In [44]: df2[df2['E'].isin(['two', 'four'])]
Out[44]:
A B C D E
2013-01-03 -0.861849 -2.104569 -0.494929 1.071804 two
2013-01-05 -0.424972 0.567020 0.276232 -1.087401 four
Setting
Setting a new column automatically aligns the data by the indexes.
In [45]: s1 = pd.Series([1, 2, 3, 4, 5, 6], index=pd.date_range('20130102', periods=6))
In [46]: s1
Out[46]:
2013-01-02 1
2013-01-03 2
2013-01-04 3
2013-01-05 4
2013-01-06 5
2013-01-07 6
Freq: D, dtype: int64
In [47]: df['F'] = s1
Setting values by label:
In [48]: df.at[dates[0], 'A'] = 0
Setting values by position:
In [49]: df.iat[0, 1] = 0
Setting by assigning with a NumPy array:
In [50]: df.loc[:, 'D'] = np.array([5] * len(df))
The result of the prior setting operations.
In [51]: df
Out[51]:
A B C D F
2013-01-01 0.000000 0.000000 -1.509059 5 NaN
2013-01-02 1.212112 -0.173215 0.119209 5 1.0
2013-01-03 -0.861849 -2.104569 -0.494929 5 2.0
2013-01-04 0.721555 -0.706771 -1.039575 5 3.0
2013-01-05 -0.424972 0.567020 0.276232 5 4.0
2013-01-06 -0.673690 0.113648 -1.478427 5 5.0
A where
operation with setting.
In [52]: df2 = df.copy()
In [53]: df2[df2 > 0] = -df2
In [54]: df2
Out[54]:
A B C D F
2013-01-01 0.000000 0.000000 -1.509059 -5 NaN
2013-01-02 -1.212112 -0.173215 -0.119209 -5 -1.0
2013-01-03 -0.861849 -2.104569 -0.494929 -5 -2.0
2013-01-04 -0.721555 -0.706771 -1.039575 -5 -3.0
2013-01-05 -0.424972 -0.567020 -0.276232 -5 -4.0
2013-01-06 -0.673690 -0.113648 -1.478427 -5 -5.0
Missing Data
pandas primarily uses the value np.nan
to represent missing data. It is by default not included in computations. See the Missing Data section.
Reindexing allows you to change/add/delete the index on a specified axis. This returns a copy of the data.
In [55]: df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
In [56]: df1.loc[dates[0]:dates[1], 'E'] = 1
In [57]: df1
Out[57]:
A B C D F E
2013-01-01 0.000000 0.000000 -1.509059 5 NaN 1.0
2013-01-02 1.212112 -0.173215 0.119209 5 1.0 1.0
2013-01-03 -0.861849 -2.104569 -0.494929 5 2.0 NaN
2013-01-04 0.721555 -0.706771 -1.039575 5 3.0 NaN
To drop any rows that have missing data.
In [58]: df1.dropna(how='any')
Out[58]:
A B C D F E
2013-01-02 1.212112 -0.173215 0.119209 5 1.0 1.0
Filling missing data.
In [59]: df1.fillna(value=5)
Out[59]:
A B C D F E
2013-01-01 0.000000 0.000000 -1.509059 5 5.0 1.0
2013-01-02 1.212112 -0.173215 0.119209 5 1.0 1.0
2013-01-03 -0.861849 -2.104569 -0.494929 5 2.0 5.0
2013-01-04 0.721555 -0.706771 -1.039575 5 3.0 5.0
To get the boolean mask where values are nan
.
In [60]: pd.isna(df1)
Out[60]:
A B C D F E
2013-01-01 False False False False True False
2013-01-02 False False False False False False
2013-01-03 False False False False False True
2013-01-04 False False False False False True
Operations
See the Basic section on Binary Ops.
Stats
Operations in general exclude missing data.
Performing a descriptive statistic:
In [61]: df.mean()
Out[61]:
A -0.004474
B -0.383981
C -0.687758
D 5.000000
F 3.000000
dtype: float64
Same operation on the other axis:
In [62]: df.mean(1)
Out[62]:
2013-01-01 0.872735
2013-01-02 1.431621
2013-01-03 0.707731
2013-01-04 1.395042
2013-01-05 1.883656
2013-01-06 1.592306
Freq: D, dtype: float64
Operating with objects that have different dimensionality and need alignment. In addition, pandas automatically broadcasts along the specified dimension.
In [63]: s = pd.Series([1, 3, 5, np.nan, 6, 8], index=dates).shift(2)
In [64]: s
Out[64]:
2013-01-01 NaN
2013-01-02 NaN
2013-01-03 1.0
2013-01-04 3.0
2013-01-05 5.0
2013-01-06 NaN
Freq: D, dtype: float64
In [65]: df.sub(s, axis='index')
Out[65]:
A B C D F
2013-01-01 NaN NaN NaN NaN NaN
2013-01-02 NaN NaN NaN NaN NaN
2013-01-03 -1.861849 -3.104569 -1.494929 4.0 1.0
2013-01-04 -2.278445 -3.706771 -4.039575 2.0 0.0
2013-01-05 -5.424972 -4.432980 -4.723768 0.0 -1.0
2013-01-06 NaN NaN NaN NaN NaN
Apply
Applying functions to the data:
In [66]: df.apply(np.cumsum)
Out[66]:
A B C D F
2013-01-01 0.000000 0.000000 -1.509059 5 NaN
2013-01-02 1.212112 -0.173215 -1.389850 10 1.0
2013-01-03 0.350263 -2.277784 -1.884779 15 3.0
2013-01-04 1.071818 -2.984555 -2.924354 20 6.0
2013-01-05 0.646846 -2.417535 -2.648122 25 10.0
2013-01-06 -0.026844 -2.303886 -4.126549 30 15.0
In [67]: df.apply(lambda x: x.max() - x.min())
Out[67]:
A 2.073961
B 2.671590
C 1.785291
D 0.000000
F 4.000000
dtype: float64
Histogramming
See more at Histogramming and Discretization.
In [68]: s = pd.Series(np.random.randint(0, 7, size=10))
In [69]: s
Out[69]:
0 4
1 2
2 1
3 2
4 6
5 4
6 4
7 6
8 4
9 4
dtype: int64
In [70]: s.value_counts()
Out[70]:
4 5
6 2
2 2
1 1
dtype: int64
String Methods
Series is equipped with a set of string processing methods in the str attribute that make it easy to operate on each element of the array, as in the code snippet below. Note that pattern-matching in str generally uses regular expressions by default (and in some cases always uses them). See more at Vectorized String Methods.
In [71]: s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
In [72]: s.str.lower()
Out[72]:
0 a
1 b
2 c
3 aaba
4 baca
5 NaN
6 caba
7 dog
8 cat
dtype: object
Merge
Concat
pandas provides various facilities for easily combining together Series, DataFrame, and Panel objects with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations.
See the Merging section.
Concatenating pandas objects together with concat()
:
In [73]: df = pd.DataFrame(np.random.randn(10, 4))
In [74]: df
Out[74]:
0 1 2 3
0 -0.548702 1.467327 -1.015962 -0.483075
1 1.637550 -1.217659 -0.291519 -1.745505
2 -0.263952 0.991460 -0.919069 0.266046
3 -0.709661 1.669052 1.037882 -1.705775
4 -0.919854 -0.042379 1.247642 -0.009920
5 0.290213 0.495767 0.362949 1.548106
6 -1.131345 -0.089329 0.337863 -0.945867
7 -0.932132 1.956030 0.017587 -0.016692
8 -0.575247 0.254161 -1.143704 0.215897
9 1.193555 -0.077118 -0.408530 -0.862495
# break it into pieces
In [75]: pieces = [df[:3], df[3:7], df[7:]]
In [76]: pd.concat(pieces)
Out[76]:
0 1 2 3
0 -0.548702 1.467327 -1.015962 -0.483075
1 1.637550 -1.217659 -0.291519 -1.745505
2 -0.263952 0.991460 -0.919069 0.266046
3 -0.709661 1.669052 1.037882 -1.705775
4 -0.919854 -0.042379 1.247642 -0.009920
5 0.290213 0.495767 0.362949 1.548106
6 -1.131345 -0.089329 0.337863 -0.945867
7 -0.932132 1.956030 0.017587 -0.016692
8 -0.575247 0.254161 -1.143704 0.215897
9 1.193555 -0.077118 -0.408530 -0.862495
Join
SQL style merges. See the Database style joining section.
In [77]: left = pd.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]})
In [78]: right = pd.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]})
In [79]: left
Out[79]:
key lval
0 foo 1
1 foo 2
In [80]: right
Out[80]:
key rval
0 foo 4
1 foo 5
In [81]: pd.merge(left, right, on='key')
Out[81]:
key lval rval
0 foo 1 4
1 foo 1 5
2 foo 2 4
3 foo 2 5
Another example that can be given is:
In [82]: left = pd.DataFrame({'key': ['foo', 'bar'], 'lval': [1, 2]})
In [83]: right = pd.DataFrame({'key': ['foo', 'bar'], 'rval': [4, 5]})
In [84]: left
Out[84]:
key lval
0 foo 1
1 bar 2
In [85]: right
Out[85]:
key rval
0 foo 4
1 bar 5
In [86]: pd.merge(left, right, on='key')
Out[86]:
key lval rval
0 foo 1 4
1 bar 2 5
Append
Append rows to a dataframe. See the Appending section.
In [87]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D'])
In [88]: df
Out[88]:
A B C D
0 1.346061 1.511763 1.627081 -0.990582
1 -0.441652 1.211526 0.268520 0.024580
2 -1.577585 0.396823 -0.105381 -0.532532
3 1.453749 1.208843 -0.080952 -0.264610
4 -0.727965 -0.589346 0.339969 -0.693205
5 -0.339355 0.593616 0.884345 1.591431
6 0.141809 0.220390 0.435589 0.192451
7 -0.096701 0.803351 1.715071 -0.708758
In [89]: s = df.iloc[3]
In [90]: df.append(s, ignore_index=True)
Out[90]:
A B C D
0 1.346061 1.511763 1.627081 -0.990582
1 -0.441652 1.211526 0.268520 0.024580
2 -1.577585 0.396823 -0.105381 -0.532532
3 1.453749 1.208843 -0.080952 -0.264610
4 -0.727965 -0.589346 0.339969 -0.693205
5 -0.339355 0.593616 0.884345 1.591431
6 0.141809 0.220390 0.435589 0.192451
7 -0.096701 0.803351 1.715071 -0.708758
8 1.453749 1.208843 -0.080952 -0.264610
Grouping
By “group by” we are referring to a process involving one or more of the following steps:
- Splitting the data into groups based on some criteria
- Applying a function to each group independently
- Combining the results into a data structure
See the Grouping section.
In [91]: df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
....: 'foo', 'bar', 'foo', 'foo'],
....: 'B': ['one', 'one', 'two', 'three',
....: 'two', 'two', 'one', 'three'],
....: 'C': np.random.randn(8),
....: 'D': np.random.randn(8)})
....:
In [92]: df
Out[92]:
A B C D
0 foo one -1.202872 -0.055224
1 bar one -1.814470 2.395985
2 foo two 1.018601 1.552825
3 bar three -0.595447 0.166599
4 foo two 1.395433 0.047609
5 bar two -0.392670 -0.136473
6 foo one 0.007207 -0.561757
7 foo three 1.928123 -1.623033
Grouping and then applying the sum()
function to the resulting groups.
In [93]: df.groupby('A').sum()
Out[93]:
C D
A
bar -2.802588 2.42611
foo 3.146492 -0.63958
Grouping by multiple columns forms a hierarchical index, and again we can apply the sum
function.
In [94]: df.groupby(['A', 'B']).sum()
Out[94]:
C D
A B
bar one -1.814470 2.395985
three -0.595447 0.166599
two -0.392670 -0.136473
foo one -1.195665 -0.616981
three 1.928123 -1.623033
two 2.414034 1.600434
Reshaping
See the sections on Hierarchical Indexing and Reshaping.
Stack
In [95]: tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
....: 'foo', 'foo', 'qux', 'qux'],
....: ['one', 'two', 'one', 'two',
....: 'one', 'two', 'one', 'two']]))
....:
In [96]: index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
In [97]: df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B'])
In [98]: df2 = df[:4]
In [99]: df2
Out[99]:
A B
first second
bar one 0.029399 -0.542108
two 0.282696 -0.087302
baz one -1.575170 1.771208
two 0.816482 1.100230
The stack()
method “compresses” a level in the DataFrame’s columns.
In [100]: stacked = df2.stack()
In [101]: stacked
Out[101]:
first second
bar one A 0.029399
B -0.542108
two A 0.282696
B -0.087302
baz one A -1.575170
B 1.771208
two A 0.816482
B 1.100230
dtype: float64
With a “stacked” DataFrame or Series (having a MultiIndex
as the index
), the inverse operation of stack()
is unstack()
, which by default unstacks the last level:
In [102]: stacked.unstack()
Out[102]:
A B
first second
bar one 0.029399 -0.542108
two 0.282696 -0.087302
baz one -1.575170 1.771208
two 0.816482 1.100230
In [103]: stacked.unstack(1)
Out[103]:
second one two
first
bar A 0.029399 0.282696
B -0.542108 -0.087302
baz A -1.575170 0.816482
B 1.771208 1.100230
In [104]: stacked.unstack(0)
Out[104]:
first bar baz
second
one A 0.029399 -1.575170
B -0.542108 1.771208
two A 0.282696 0.816482
B -0.087302 1.100230
Pivot Tables
See the section on Pivot Tables.
In [105]: df = pd.DataFrame({'A': ['one', 'one', 'two', 'three'] * 3,
.....: 'B': ['A', 'B', 'C'] * 4,
.....: 'C': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
.....: 'D': np.random.randn(12),
.....: 'E': np.random.randn(12)})
.....:
In [106]: df
Out[106]:
A B C D E
0 one A foo 1.418757 -0.179666
1 one B foo -1.879024 1.291836
2 two C foo 0.536826 -0.009614
3 three A bar 1.006160 0.392149
4 one B bar -0.029716 0.264599
5 one C bar -1.146178 -0.057409
6 two A foo 0.100900 -1.425638
7 three B foo -1.035018 1.024098
8 one C foo 0.314665 -0.106062
9 one A bar -0.773723 1.824375
10 two B bar -1.170653 0.595974
11 three C bar 0.648740 1.167115
We can produce pivot tables from this data very easily:
In [107]: pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'])
Out[107]:
C bar foo
A B
one A -0.773723 1.418757
B -0.029716 -1.879024
C -1.146178 0.314665
three A 1.006160 NaN
B NaN -1.035018
C 0.648740 NaN
two A NaN 0.100900
B -1.170653 NaN
C NaN 0.536826
Time Series
pandas has simple, powerful, and efficient functionality for performing resampling operations during frequency conversion (e.g., converting secondly data into 5-minutely data). This is extremely common in, but not limited to, financial applications. See the Time Series section.
In [108]: rng = pd.date_range('1/1/2012', periods=100, freq='S')
In [109]: ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
In [110]: ts.resample('5Min').sum()
Out[110]:
2012-01-01 25083
Freq: 5T, dtype: int64
Time zone representation:
In [111]: rng = pd.date_range('3/6/2012 00:00', periods=5, freq='D')
In [112]: ts = pd.Series(np.random.randn(len(rng)), rng)
In [113]: ts
Out[113]:
2012-03-06 0.464000
2012-03-07 0.227371
2012-03-08 -0.496922
2012-03-09 0.306389
2012-03-10 -2.290613
Freq: D, dtype: float64
In [114]: ts_utc = ts.tz_localize('UTC')
In [115]: ts_utc
Out[115]:
2012-03-06 00:00:00+00:00 0.464000
2012-03-07 00:00:00+00:00 0.227371
2012-03-08 00:00:00+00:00 -0.496922
2012-03-09 00:00:00+00:00 0.306389
2012-03-10 00:00:00+00:00 -2.290613
Freq: D, dtype: float64
Converting to another time zone:
In [116]: ts_utc.tz_convert('US/Eastern')
Out[116]:
2012-03-05 19:00:00-05:00 0.464000
2012-03-06 19:00:00-05:00 0.227371
2012-03-07 19:00:00-05:00 -0.496922
2012-03-08 19:00:00-05:00 0.306389
2012-03-09 19:00:00-05:00 -2.290613
Freq: D, dtype: float64
Converting between time span representations:
In [117]: rng = pd.date_range('1/1/2012', periods=5, freq='M')
In [118]: ts = pd.Series(np.random.randn(len(rng)), index=rng)
In [119]: ts
Out[119]:
2012-01-31 -1.134623
2012-02-29 -1.561819
2012-03-31 -0.260838
2012-04-30 0.281957
2012-05-31 1.523962
Freq: M, dtype: float64
In [120]: ps = ts.to_period()
In [121]: ps
Out[121]:
2012-01 -1.134623
2012-02 -1.561819
2012-03 -0.260838
2012-04 0.281957
2012-05 1.523962
Freq: M, dtype: float64
In [122]: ps.to_timestamp()
Out[122]:
2012-01-01 -1.134623
2012-02-01 -1.561819
2012-03-01 -0.260838
2012-04-01 0.281957
2012-05-01 1.523962
Freq: MS, dtype: float64
Converting between period and timestamp enables some convenient arithmetic functions to be used. In the following example, we convert a quarterly frequency with year ending in November to 9am of the end of the month following the quarter end:
In [123]: prng = pd.period_range('1990Q1', '2000Q4', freq='Q-NOV')
In [124]: ts = pd.Series(np.random.randn(len(prng)), prng)
In [125]: ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9
In [126]: ts.head()
Out[126]:
1990-03-01 09:00 -0.902937
1990-06-01 09:00 0.068159
1990-09-01 09:00 -0.057873
1990-12-01 09:00 -0.368204
1991-03-01 09:00 -1.144073
Freq: H, dtype: float64
Categoricals
pandas can include categorical data in a DataFrame
. For full docs, see the categorical introduction and the API documentation.
In [127]: df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6],
.....: "raw_grade": ['a', 'b', 'b', 'a', 'a', 'e']})
.....:
Convert the raw grades to a categorical data type.
In [128]: df["grade"] = df["raw_grade"].astype("category")
In [129]: df["grade"]
Out[129]:
0 a
1 b
2 b
3 a
4 a
5 e
Name: grade, dtype: category
Categories (3, object): [a, b, e]
Rename the categories to more meaningful names (assigning to Series.cat.categories
is inplace!).
In [130]: df["grade"].cat.categories = ["very good", "good", "very bad"]
Reorder the categories and simultaneously add the missing categories (methods under Series .cat
return a new Series
by default).
In [131]: df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium",
.....: "good", "very good"])
.....:
In [132]: df["grade"]
Out[132]:
0 very good
1 good
2 good
3 very good
4 very good
5 very bad
Name: grade, dtype: category
Categories (5, object): [very bad, bad, medium, good, very good]
Sorting is per order in the categories, not lexical order.
In [133]: df.sort_values(by="grade")
Out[133]:
id raw_grade grade
5 6 e very bad
1 2 b good
2 3 b good
0 1 a very good
3 4 a very good
4 5 a very good
Grouping by a categorical column also shows empty categories.
In [134]: df.groupby("grade").size()
Out[134]:
grade
very bad 1
bad 0
medium 0
good 2
very good 3
dtype: int64
Plotting
See the Plotting docs.
In [135]: ts = pd.Series(np.random.randn(1000),
.....: index=pd.date_range('1/1/2000', periods=1000))
.....:
In [136]: ts = ts.cumsum()
In [137]: ts.plot()
Out[137]: <matplotlib.axes._subplots.AxesSubplot at 0x7f7a2fc08240>
On a DataFrame, the plot()
method is a convenience to plot all of the columns with labels:
In [138]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,
.....: columns=['A', 'B', 'C', 'D'])
.....:
In [139]: df = df.cumsum()
In [140]: plt.figure()
Out[140]: <Figure size 640x480 with 0 Axes>
In [141]: df.plot()
Out[141]: <matplotlib.axes._subplots.AxesSubplot at 0x7f7a2bf762b0>
In [142]: plt.legend(loc='best')
Out[142]: <matplotlib.legend.Legend at 0x7f7a2beac748>
Getting Data In/Out
CSV
In [143]: df.to_csv('foo.csv')
In [144]: pd.read_csv('foo.csv')
Out[144]:
Unnamed: 0 A B C D
0 2000-01-01 0.266457 -0.399641 -0.219582 1.186860
1 2000-01-02 -1.170732 -0.345873 1.653061 -0.282953
2 2000-01-03 -1.734933 0.530468 2.060811 -0.515536
3 2000-01-04 -1.555121 1.452620 0.239859 -1.156896
4 2000-01-05 0.578117 0.511371 0.103552 -2.428202
5 2000-01-06 0.478344 0.449933 -0.741620 -1.962409
6 2000-01-07 1.235339 -0.091757 -1.543861 -1.084753
.. ... ... ... ... ...
993 2002-09-20 -10.628548 -9.153563 -7.883146 28.313940
994 2002-09-21 -10.390377 -8.727491 -6.399645 30.914107
995 2002-09-22 -8.985362 -8.485624 -4.669462 31.367740
996 2002-09-23 -9.558560 -8.781216 -4.499815 30.518439
997 2002-09-24 -9.902058 -9.340490 -4.386639 30.105593
998 2002-09-25 -10.216020 -9.480682 -3.933802 29.758560
999 2002-09-26 -11.856774 -10.671012 -3.216025 29.369368
[1000 rows x 5 columns]
HDF5
Reading and writing to HDFStores.
Writing to a HDF5 Store.
In [145]: df.to_hdf('foo.h5', 'df')
Reading from a HDF5 Store.
In [146]: pd.read_hdf('foo.h5', 'df')
Out[146]:
A B C D
2000-01-01 0.266457 -0.399641 -0.219582 1.186860
2000-01-02 -1.170732 -0.345873 1.653061 -0.282953
2000-01-03 -1.734933 0.530468 2.060811 -0.515536
2000-01-04 -1.555121 1.452620 0.239859 -1.156896
2000-01-05 0.578117 0.511371 0.103552 -2.428202
2000-01-06 0.478344 0.449933 -0.741620 -1.962409
2000-01-07 1.235339 -0.091757 -1.543861 -1.084753
... ... ... ... ...
2002-09-20 -10.628548 -9.153563 -7.883146 28.313940
2002-09-21 -10.390377 -8.727491 -6.399645 30.914107
2002-09-22 -8.985362 -8.485624 -4.669462 31.367740
2002-09-23 -9.558560 -8.781216 -4.499815 30.518439
2002-09-24 -9.902058 -9.340490 -4.386639 30.105593
2002-09-25 -10.216020 -9.480682 -3.933802 29.758560
2002-09-26 -11.856774 -10.671012 -3.216025 29.369368
[1000 rows x 4 columns]
Excel
Reading and writing to MS Excel.
Writing to an excel file.
In [147]: df.to_excel('foo.xlsx', sheet_name='Sheet1')
Reading from an excel file.
In [148]: pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA'])
Out[148]:
Unnamed: 0 A B C D
0 2000-01-01 0.266457 -0.399641 -0.219582 1.186860
1 2000-01-02 -1.170732 -0.345873 1.653061 -0.282953
2 2000-01-03 -1.734933 0.530468 2.060811 -0.515536
3 2000-01-04 -1.555121 1.452620 0.239859 -1.156896
4 2000-01-05 0.578117 0.511371 0.103552 -2.428202
5 2000-01-06 0.478344 0.449933 -0.741620 -1.962409
6 2000-01-07 1.235339 -0.091757 -1.543861 -1.084753
.. ... ... ... ... ...
993 2002-09-20 -10.628548 -9.153563 -7.883146 28.313940
994 2002-09-21 -10.390377 -8.727491 -6.399645 30.914107
995 2002-09-22 -8.985362 -8.485624 -4.669462 31.367740
996 2002-09-23 -9.558560 -8.781216 -4.499815 30.518439
997 2002-09-24 -9.902058 -9.340490 -4.386639 30.105593
998 2002-09-25 -10.216020 -9.480682 -3.933802 29.758560
999 2002-09-26 -11.856774 -10.671012 -3.216025 29.369368
[1000 rows x 5 columns]
Gotchas¶
If you are attempting to perform an operation you might see an exception like:
>>> if pd.Series([False, True, False]):
... print("I was true")
Traceback
...
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
See Comparisons for an explanation and what to do.
See Gotchas as well.