Pandas

Eric讨论 | 贡献2020年11月4日 (三) 06:01的版本 →‎属性和方法

Pandas是一个Python语言的开源软件库,用于数据分析,可以方便对数据进行处理、计算、分析、存储及可视化。

简介

时间轴

  • 2008年,开发者Wes McKinney在AQR Capital Management开始制作pandas来满足在财务数据上进行定量分析对高性能、灵活工具的需要。在离开AQR之前他说服管理者允许他将这个库开放源代码。
  • 2012年,另一个AQR雇员Chang She加入了这项努力并成为这个库的第二个主要贡献者。
  • 2015年,Pandas签约了NumFOCUS的一个财务赞助项目,它是美国的501(c)(3)非营利慈善团体。

安装和导入

使用pip安装Pandas

pip install pandas

如果使用的是Anaconda等计算科学软件包,已经安装好了pandas库。

导入Pandas,在脚本顶部导入,一般写法如下:

import pandas as pd

查看Pandas版本:

pd.__version__

数据结构

pandas定义了2种数据类型,Series和DataFrame,大部分操作都在这两种数据类型上进行。

了解更多 >> Pandas 用户指南:数据结构


Series

Series是一个有轴标签(索引)的一维数组,能够保存任何数据类型(整数,字符串,浮点数,Python对象等)。轴标签称为index。和Python字典类似。

创建Series的基本方法为,使用pandas.Series类新建一个Series对象,格式如下:

pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)

轴标签index不是必须,如果省略,轴标签默认为从0开始的整数数组。一些示例如下:

s = pd.Series(["foo", "bar", "foba"])
print(type(s))   #<class 'pandas.core.series.Series'>

s2 = pd.Series(["foo", "bar", "foba"], index=['b','d','c'])

# 创建日期索引
date_index = pd.date_range("2020-01-01", periods=3, freq="D")
s3 = pd.Series(["foo", "bar", "foba"], index=date_index)

了解更多 >> Pandas 用户指南:Series


DataFrame

DataFrame是有标记的二维的数据结构,具有可能不同类型的列。由数据,行标签(索引,index),列标签(列,columns)构成。您可以将其视为电子表格或SQL表,或Series对象的字典。它通常是最常用的Pandas对象。

创建DataFrame对象有多种方法:

  • 使用pandas.DataFrame()构造方法
  • 使用pandas.DataFrame.from_dict()方法,类似构造方法
  • 使用pandas.DataFrame.from_records()方法,类似构造方法
  • 使用函数从导入文件创建,如使用pandas.read_csv()函数导入csv文件创建一个DataFrame对象。

构造方法pandas.DataFrame()的格式为:

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

了解更多 >> Pandas 用户指南:DataFrame


属性和方法

下面将Series和DataFrame的属性、方法按作用分类展示。

表示例中s为一个Series对象,df为一个DataFrame对象:

>>> s = pd.Series(['a', 'b', 'c'])
>>> s
0    a
1    b
2    c
dtype: object

>>> df = pd.DataFrame([['foo', 22], ['bar', 25], ['test', 18]],columns=['name', 'age'])
>>> df

了解更多 >> Pandas API:DataFrame Pandas API:Series


构造方法

方法名 描述 Series DataFrame 示例
构造方法 创建一个Series对象或DataFrame对象 pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False) pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False) s = pd.Series(["a", "b", "c"])

df = pd.DataFrame([['foo', 22], ['bar', 25], ['test', 18]],columns=['name', 'age'])

属性和基本信息

属性/方法 描述 Series DataFrame 示例
index 索引(行标签) Series.index DataFrame.index s.index返回RangeIndex(start=0, stop=3, step=1)
df.index
columns 列标签,Series无 DataFrame.columns df.columns
axes 返回轴标签(行标签和列标签)的列表。
Series返回[index]
DataFrame返回[index, columns]
Series.axes DataFrame.axes s.axes返回[RangeIndex(start=0, stop=3, step=1)]
dtypes 返回数据的Numpy数据类型(dtype对象) Series.index DataFrame.index s.dtypes
df.dtypes
dtype 返回数据的Numpy数据类型(dtype对象) Series.index s.dtype
array 返回 Series 或 Index 数据的数组,该数组为pangdas扩展的python数组. Series.index s.array
返回:<PandasArray>
['a', 'b', 'c']
Length: 3, dtype: object
attrs 此对象全局属性字典。 Series.attrs DataFrame.attrs s.attrs返回{}
hasnans 如果有任何空值(如Python的None,np.NaN)返回True,否则返回False。 Series.hasnans s.hasnans
返回False
values 返回ndarray(NumPy的多维数组)或类似ndarray的形式。 Series.values DataFrame.values s.values返回array(['a', 'b', 'c'], dtype=object)
ndim 返回数据的维数,Series返回1,DataFrame返回2 Series.ndim DataFrame.ndim s.ndim返回1
df.ndim返回2
size 返回数据中元素的个数 Series.size DataFrame.size s.size返回3
df.ndim返回6
shape 返回数据形状(行数和列数)的元组 Series.shape DataFrame.shape s.shape返回(3, )
df.shape返回(3, 2)
empty 返回是否为空,为空返回Ture Series.empty DataFrame.empty s.empty返回False
df.empty返回False
name 返回Series的名称。 Series.name s.name返回空
memory_usage() 返回Series或DataFrame的内存使用情况,单位Bytes。参数index默认为True,表示包含index。
参数deep默认为False,表示不通过查询dtypes对象来深入了解数据的系统级内存使用情况
Series.memory_usage(index=True, deep=False) DataFrame.memory_usage(index=True, deep=False) s.memory_usage()返回空152
df.memory_usage(index=False)
info() 打印DataFrame的简要信息。 DataFrame.info(verbose=True, buf=None, max_cols=None, memory_usage=True, null_counts=True) df.info()
select_dtypes() 根据列的dtypes返回符合条件的DataFrame子集 DataFrame.select_dtypes(include=None, exclude=None) df.select_dtypes(include=['float64'])

数据选取/索引标签/迭代

属性/方法 描述 Series DataFrame 示例
head() 返回前n行数据,默认前5行 Series.head(n=5) DataFrame.head(n=5) df.head()返回df前5行数据
df.head(10)返回df前10行数据。
tail() 返回最后n行数据,默认最后5行 Series.tail(n=5) DataFrame.tail(n=5) df.tail()返回df最后5行数据
df.tail(10)返回df最后10行数据。
at 通过行轴和列轴标签对获取或设置单个值。 Series.at DataFrame.at s.at[1]返回'b'
s.at[2]='d'设置索引位置为第三的值等于'd'
df.at[2, 'name']'获取index=2,columns='name'点的值
iat 通过行轴和列轴整数位置获取或设置单个值。 Series.iat DataFrame.iat s.iat[1]
s.iat[2]='d'
loc 通过标签值或布尔数组访问一组行和列。 Series.loc DataFrame.loc df.loc[2]选取索引(行标签)值为2的行
df.loc[1:2] 选取索引值为1到2的行
df.loc[[1,2]]选取索引值为1和2的行
df.loc[1,'name']选取行标签值为1,列标签值为'name'的单个值
df.loc[[1:2],'name']选取行标签值为1到2,列标签值为'name'的数据
iloc 通过标签整数位置或布尔数组访问一组行和列。 Series.iloc DataFrame.iloc s.iloc[2]选取行标签位置为2的行
s.iloc[:2] 选取索引为0到2(不包含2)的值
s.iloc[[True,False,True]]选取索引位置为True的值
s.iloc[lambda x: x.index % 2 == 0]选取索引为双数的值
insert 在指定位置插入列。 DataFrame.insert(loc, column, value, allow_duplicates=False)
__iter__() Series返回值的迭代器
DataFrame返回轴的迭代器
Series.__iter__() DataFrame.__iter__() s.__iter__()
items() Series遍历,返回索引和值的迭代器
DataFrame按列遍历,返回列标签和列的Series对迭代器。
Series.items() DataFrame.items() s.items()
df.items()
for label, content in df.items():
iteritems() 返回可迭代的键值对,Series返回索引和值,DataFrame返回列名和列。 Series.iteritems() DataFrame.iteritems()
keys() Get the ‘info axis’ Series.keys() DataFrame.keys()
iterrows() Iterate over DataFrame rows as (index, Series) pairs. DataFrame.iterrows()
itertuples() Iterate over DataFrame rows as namedtuples. DataFrame.itertuples(index=True, name='Pandas')
lookup() Label-based “fancy indexing” function for DataFrame. DataFrame.lookup(row_labels, col_labels)
pop() Return item and drop from frame. Series.pop(item) DataFrame.pop(item)
xs() Return cross-section from the Series/DataFrame. Series.xs(key, axis=0, level=None, drop_level=True) DataFrame.xs(key, axis=0, level=None, drop_level=True)
get() Get item from object for given key (ex: DataFrame column). Series.get(key, default=None) DataFrame.get(key, default=None)
isin() Whether each element in the Series/DataFrame is contained in values. Series.isin(values) DataFrame.isin(values)
where() Replace values where the condition is False. Series.where(cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False) DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False)
mask() Replace values where the condition is True. Series.mask(cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False) DataFrame.mask(cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False)
query() Query the columns of a DataFrame with a boolean expression. DataFrame.query(expr, inplace=False, **kwargs) df.query('A > B')相当于df[df.A > df.B]
add_prefix() 索引或列标签添加前缀 Series.add_prefix(prefix) DataFrame.add_prefix(prefix) s.add_prefix('item_')
df.add_prefix('col_')
add_suffix() 索引或列标签添加后缀 Series.add_suffix(suffix) DataFrame.add_suffix(suffix)
align() Align two objects on their axes with the specified join method. Series.align(other, join='outer', axis=None, level=None, copy=True, fill_value=None, method=None, limit=None, fill_axis=0, broadcast_axis=None) DataFrame.align(other, join='outer', axis=None, level=None, copy=True, fill_value=None, method=None, limit=None, fill_axis=0, broadcast_axis=None)
at_time() select values at particular time of day (e.g., 9:30AM). Series.at_time(time, asof=False, axis=None) DataFrame.at_time(time, asof=False, axis=None)
between_time() Select values between particular times of the day (e.g., 9:00-9:30 AM). Series.between_time(start_time, end_time, include_start=True, include_end=True, axis=None) DataFrame.between_time(start_time, end_time, include_start=True, include_end=True, axis=None) df2.between_time('0:15', '0:45')
drop() Drop specified labels from rows or columns. Series.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise') DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
drop_duplicates() Return Series with duplicate values removed.
Return DataFrame with duplicate rows removed.
Series.drop_duplicates(keep='first', inplace=False) DataFrame.drop_duplicates(subset=None, keep='first', inplace=False, ignore_index=False)
duplicated() Indicate duplicate Series values.
Return boolean Series denoting duplicate rows.
Series.duplicated(keep='first') DataFrame.duplicated(subset=None, keep='first')
equals() Test whether two objects contain the same elements. Series.equals(other) DataFrame.equals(other) df.equals(df2)
filter() Subset the dataframe rows or columns according to the specified index labels. Series.filter(items=None, like=None, regex=None, axis=None) DataFrame.filter(items=None, like=None, regex=None, axis=None) df.filter(like='bbi', axis=0)选取行标签包含'bbi'的行。
first() Select initial periods of time series data based on a date offset. Series.first(offset) DataFrame.first(offset)
last() Select final periods of time series data based on a date offset. Series.last(offset) DataFrame.last(offset)
idxmax() 返回第一次出现最大值的轴标签。 Series.idxmax(axis=0, skipna=True, *args, **kwargs) DataFrame.idxmax(axis=0, skipna=True) df.idxmax()
idxmin() 返回第一次出现最小值的轴标签。 Series.idxmin(axis=0, skipna=True, *args, **kwargs) DataFrame.idxmin(axis=0, skipna=True) s.idxmin()
reindex() Conform Series/DataFrame to new index with optional filling logic. Series.reindex(index=None, **kwargs) DataFrame.reindex(**kwargs)
reindex_like() Return an object with matching indices as other object. Series.reindex_like(other, method=None, copy=True, limit=None, tolerance=None) DataFrame.reindex_like(other, method=None, copy=True, limit=None, tolerance=None)
rename() Alter axes labels. Series.rename(index=None, *, axis=None, copy=True, inplace=False, level=None, errors='ignore') DataFrame.rename(**kwargs)
rename_axis() Set the name of the axis for the index or columns. Series.rename_axis(**kwargs) DataFrame.rename_axis(**kwargs)
set_index() Set the DataFrame index using existing columns. DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False) df.set_index('col_3')将‘col_3’列设置为索引。
reset_index() Reset the index, or a level of it. Series.reset_index(level=None, drop=False, name=None, inplace=False) DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=)
sample() Return a random sample of items from an axis of object. Series.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None) DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
set_axis() Assign desired index to given axis. Series.set_axis(labels, axis=0, inplace=False) DataFrame.set_axis(labels, axis=0, inplace=False) df.set_axis(['a', 'b', 'c'], axis='index')
df.set_axis(['I', 'II'], axis='columns')
take() Return the elements in the given positional indices along an axis. Series.take(indices, axis=0, is_copy=None, **kwargs) DataFrame.take(indices, axis=0, is_copy=None, **kwargs)
truncate() Truncate a Series or DataFrame before and after some index value. Series.truncate(before=None, after=None, axis=None, copy=True) DataFrame.truncate(before=None, after=None, axis=None, copy=True)

计算/描述统计

属性/方法 描述 Series DataFrame 示例
abs() 返回 Series/DataFrame 每个元素的绝对值。 Series.abs() DataFrame.abs() s.abs()
df.abs()
all() Return whether all elements are True, potentially over an axis. Series.all(axis=0, bool_only=None, skipna=True, level=None, **kwargs) DataFrame.all(axis=0, bool_only=None, skipna=True, level=None, **kwargs)
any() Return whether any element is True, potentially over an axis. Series.any(axis=0, bool_only=None, skipna=True, level=None, **kwargs) DataFrame.any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)
clip() Trim values at input threshold(s). Series.clip(lower=None, upper=None, axis=None, inplace=False, *args, **kwargs) DataFrame.clip(lower=None, upper=None, axis=None, inplace=False, *args, **kwargs)
corr() Compute pairwise correlation of columns, excluding NA/null values. Series.corr(other, method='pearson', min_periods=None) DataFrame.corr(method='pearson', min_periods=1)
corrwith() Compute pairwise correlation. DataFrame.corrwith(other, axis=0, drop=False, method='pearson')
count() 统计每行或每列值的个数,不包括NA值。 Series.count(level=None) DataFrame.count(axis=0, level=None, numeric_only=False) s.count()
df.count()
df.count(axis='columns')
cov() Compute pairwise covariance of columns, excluding NA/null values.
cummax() Return cumulative maximum over a DataFrame or Series axis.
cummin() Return cumulative minimum over a DataFrame or Series axis.
cumprod() Return cumulative product over a DataFrame or Series axis.
cumsum() Return cumulative sum over a DataFrame or Series axis.
describe() Generate descriptive statistics.
diff() First discrete difference of element.
eval() Evaluate a string describing operations on DataFrame columns.
kurt() Return unbiased kurtosis over requested axis.
kurtosis() Return unbiased kurtosis over requested axis.
mad() Return the mean absolute deviation of the values for the requested axis.
max() Return the maximum of the values for the requested axis.
mean() Return the mean of the values for the requested axis.
median() Return the median of the values for the requested axis.
min() Return the minimum of the values for the requested axis.
mode() Get the mode(s) of each element along the selected axis.
pct_change() Percentage change between the current and a prior element.
prod() Return the product of the values for the requested axis.
product() Return the product of the values for the requested axis.
quantile() Return values at the given quantile over requested axis.
rank() Compute numerical data ranks (1 through n) along axis.
round() Round a DataFrame to a variable number of decimal places.
sem() Return unbiased standard error of the mean over requested axis.
skew() Return unbiased skew over requested axis.
sum() Return the sum of the values for the requested axis.
std() Return sample standard deviation over requested axis.
var() Return unbiased variance over requested axis.
nunique() Count distinct observations over requested axis.
value_counts() Return a Series containing counts of unique rows in the

索引与轴标签

查看索引

 s.index  #Series 索引
 df.index  #DataFrame 索引(行标签)
 df.columns #DataFrame 列标签

重新设置索引

Series对象和DataFrame对象都由reindex()方法


数据选取

选取概览

方法 描述 示例
索引运算符[ ] Python中序列对象使用self[key]是在调用对象的特殊方法__getitem__() 。Python运算符[ ]有3种通用序列操作:
1.self[i] 取第i项(起始为0)
2.self[i:j] 从 i 到 j 的切片
3.self[i:j:k] s 从 i 到 j 步长为 k 的切片
Pandas支持NumPy扩展的一些操作:
1.self[布尔索引],如s[s>5]
s[1] 取s的第二个值
df[1:-1]切片,返回df第二行到倒数第二行组成的DataFrame对象
属性运算符. 同Python字典属性获取
按标签选择loc[ ] 基于标签的索引方法,通过对象调用.loc属性生成序列对象,序列对象调用索引运算符[]
按位置选择iloc[ ] 纯粹基于整数位置的索引方法,通过对象调用.iloc属性生成序列对象,然后序列对象调用索引运算符[]

了解更多 >> Pandas 指南:索引与选择数据 Python 3 文档:序列类型 - 通用序列操作 Python 3 文档:数据模型 - 特殊方法名称 NumPy 文档:初学者基础知识 - 索引和切片


按标签选择

pandas提供基于标签的索引方法,通过对象调用.loc属性生成序列对象,序列对象调用索引运算符[]。该方法严格要求,每个标签都必须在索引中,否则会抛出KeyError错误。切片时,如果索引中存在起始边界和终止边界,则都将包括在内。整数是有效的标签,但它们引用的是标签,而不是位置(索引顺序)。

.loc索引输入值 描述 Series示例 DataFrame示例
单个标签 例如5或'a'(注意,5被解释为索引的标签,而不是整数位置。) s.loc['a'] 返回s索引为'a'的值 df.loc['b'] 返回df索引(行标签)为'b'的行(Series对象)
标签列表或标签数组 如['a', 'c'](注意:这种方式会有两组方括号[[]],里面是生成列表,外面是索引取值操作) s.loc[['a', 'c']]返回s索引为'a'和'c'的值(Series对象) df.loc[['a', 'c']]返回df索引(行标签)为'a'和'c'的行(DataFrame对象)
带标签的切片对象 切片如 'a':'f'表示标签'a'到标签'f',步长切片如 'a':'f':2表示标签'a'到标签'f'按步长2选取(注意:和Python切片不同,这里包含开始标签和结束标签),还有一些常用示例如:
'f':从标签'f'开始到最后
:'f'从最开始到标签'f'
:全部标签
s.loc[a:c] 返回s索引'a'到'c'的值 df.loc[b:f] 返回df索引(行标签)'b'到'f'的行(DataFrame对象)
行标签,列标签 只有DataFrame可用,格式行标签,列标签,行标签或列标签可以使用切片或数组等。 df.loc['a','name']选取索引为'a',列标签为'name'的单个值。
df.loc['a':'c','name' ]返回Series对象
df.loc['a':'c','id':'name' ]返回DataFrame对象
布尔数组 如[True, False, True]。注意布尔数组长度要与轴标签长度相同,否则会抛出IndexError错误。 s.loc[[True, False, True]] 返回s的第1个和第3个值 df.loc[[False, True, True]] 返回df的第2行和第3行
callable function 会返回上面的一种索引形式

了解更多 >> Pandas 指南:索引与选择数据 - 按标签选择 Pandas 参考:DataFrame对象 - DataFrame.loc Pandas 参考:Series对象 - Series.loc


按位置选择

pandas还提供纯粹基于整数位置的索引方法,通过对象调用.iloc属性生成序列对象,然后序列对象调用索引运算符[]。尝试使用非整数,即使有效标签也会引发IndexError。索引是从0开始的整数。切片时,包含起始索引,不包含结束索引。

.iloc索引输入值 描述 Series示例 DataFrame示例
单个整数 例如3 s.iloc[0] 返回s位置索引为0的值,即第一值 df.iloc[5] 返回df索引为5的行(Series对象),即df的第六行的
整数列表或数组 如[0,5](注意:这种方式会有两组方括号[[]],里面是生成列表,外面是索引取值操作) s.iloc[[0,5]]返回s索引为0和5的值(Series对象) df.iloc[[2,5]]返回df索引为2和5的行(DataFrame对象)
带标签的切片对象 切片如 3:5表示索引3到索引5,步长切片如 0:5:2表示索引0到索引5按步长2选取,还有一些常用示例如:
2:从索引2开始到最后
:6从最开始到索引6
:全部索引
s.iloc[3:5] 返回s索引3到索引5的值 df.iloc[3:5] 返回df索引3到索引5的行(DataFrame对象)
行位置索引,列位置索引 只有DataFrame可用,格式行位置索引,列位置索引,行位置或列位置可以使用切片或数组等。 df.iloc[0, 2]选取第1行第3列的单个值。
df.iloc[2:5, 6 ]返回第3行到5行中的第7列(Series对象)
df.iloc[2:5, 0:2 ]返回Data第3行到5行中的第1列到第2列(Frame对象)
布尔数组 如[True, False, True]。注意布尔数组长度要与轴标签长度相同,否则会抛出IndexError错误。 s.iloc[[True, False, True]] 返回s的第1个和第3个值 df.iloc[[False, True, True]] 返回df的第2行和第3行
callable function 会返回上面的一种索引形式

了解更多 >> Pandas 指南:索引与选择数据 - 按位置选择 Pandas 参考:DataFrame对象 - DataFrame.iloc Pandas 参考:Series对象 - Series.iloc


GroupBy分组

创建GroupBy对象

类名 创建对象方法 完整参数 示例
SeriesGroupBy Series.groupby() Series.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True)
DataFrameGroupBy DataFrame.groupby() DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True) df.groupby('code')df.groupby(by='code')按code列分组,创建一个GroupBy对象


GroupBy属性与方法

选取与迭代

属性/方法 描述 示例
GroupBy.__iter__() Groupby迭代器
GroupBy.groups Dict{组名->组数据} for name, group in grouped:
    print(name)
    print(group )
GroupBy.indices Dict{组名->组索引}
GroupBy.get_group(name, obj=None) 通过组名选取一个组,返回DataFrame格式。 grouped.get_group('AAPL')
pandas.Grouper(*args, **kwargs) x.describe()

功能应用

属性/方法 描述 Series DataFrame 示例
GroupBy.apply() 应用,按组应用函数func,并将结果组合在一起。 GroupBy.apply(func,* args,** kwargs) GroupBy.apply(func,* args,** kwargs) grouped['C'].apply(lambda x: x.describe())
GroupBy.agg() 聚合,等效aggregate() GroupBy.agg(func,* args,** kwargs) GroupBy.agg(func,* args,** kwargs)
aggregate() 聚合,在指定轴上使用一项或多项操作进行汇总。 SeriesGroupBy.aggregate(func=None, *args, engine=None, engine_kwargs=None, **kwargs) DataFrameGroupBy.aggregate(func=None, *args, engine=None, engine_kwargs=None, **kwargs)
transform() 转换,按组调用函数,并将原始数据替换为转换后的结果 SeriesGroupBy.transform(func, *args, engine=None, engine_kwargs=None, **kwargs) DataFrameGroupBy.transform(func, *args, engine=None, engine_kwargs=None, **kwargs)
GroupBy.pipe() 将带有参数的函数func应用于GroupBy对象,并返回函数的结果。 GroupBy.pipe(func,* args,** kwargs) GroupBy.pipe(func,* args,** kwargs)

计算/描述统计

属性/方法 描述 Series DataFrame 示例
GroupBy.all() Return True if all values in the group are truthful, else False. GroupBy.all(skipna=True) DataFrameGroupBy.all(skipna=True)
GroupBy.any() Return True if any value in the group is truthful, else False. GroupBy.any(skipna=True) DataFrameGroupBy.any(skipna=True)
GroupBy.backfill() Backward fill the values. GroupBy.backfill(limit=None) DataFrameGroupBy.backfill(limit=None)
GroupBy.bfill() 同 GroupBy.backfill() GroupBy.bfill(limit=None) DataFrameGroupBy.bfill(limit=None)
GroupBy.count() 统计每组值的个数,不包含缺失值。 GroupBy.count() DataFrameGroupBy.count() grouped.count()
GroupBy.cumcount() Number each item in each group from 0 to the length of that group - 1. GroupBy.cumcount(ascending=True) DataFrameGroupBy.cumcount(ascending=True)
GroupBy.cummax() Cumulative max for each group. GroupBy.cummax(axis=0, **kwargs) DataFrameGroupBy.cummax(axis=0, **kwargs)
GroupBy.cummin() Cumulative min for each group. GroupBy.cummin(axis=0, **kwargs) DataFrameGroupBy.cummin(axis=0, **kwargs)
GroupBy.cumprod() Cumulative product for each group. GroupBy.cumprod(axis=0, *args, **kwargs) DataFrameGroupBy.cumprod(axis=0, *args, **kwargs)
GroupBy.cumsum() Cumulative sum for each group. GroupBy.cumsum(axis=0, *args, **kwargs) DataFrameGroupBy.cumsum(axis=0, *args, **kwargs)
GroupBy.ffill() Forward fill the values. GroupBy.ffill(limit=None) DataFrameGroupBy.ffill(limit=None)
GroupBy.first() Compute first of group values. GroupBy.first(numeric_only=False, min_count=- 1)
GroupBy.head() 返回每组的前n行,默认5行 GroupBy.head(n=5)
GroupBy.last() Compute last of group values. GroupBy.last(numeric_only=False, min_count=- 1)
GroupBy.max() Compute max of group values. GroupBy.max(numeric_only=False, min_count=- 1)
GroupBy.mean() Compute mean of groups, excluding missing values. GroupBy.mean(numeric_only=True)
GroupBy.median() Compute median of groups, excluding missing values. GroupBy.median(numeric_only=True)
GroupBy.min([numeric_only, min_count]) Compute min of group values. GroupBy.min(numeric_only=False, min_count=- 1)
GroupBy.ngroup([ascending]) Number each group from 0 to the number of groups - 1. GroupBy.ngroup(ascending=True)
GroupBy.nth(n[, dropna]) 如果参数n是一个整数,则取每个组的第n行;如果n是一个整数列表,则取每组行的子集。 GroupBy.nth(n, dropna=None)
GroupBy.ohlc() 计算组的开始值,最高值,最低值和末尾值,不包括缺失值。 GroupBy.ohlc()
GroupBy.pad() Forward fill the values. GroupBy.pad(limit=None) DataFrameGroupBy.pad(limit=None)
GroupBy.prod([numeric_only, min_count]) Compute prod of group values. GroupBy.prod(numeric_only=True, min_count=0)
GroupBy.rank([method, ascending, na_option, …]) Provide the rank of values within each group. GroupBy.rank(method='average', ascending=True, na_option='keep', pct=False, axis=0) DataFrameGroupBy.rank(method='average', ascending=True, na_option='keep', pct=False, axis=0)
GroupBy.pct_change([periods, fill_method, …]) Calculate pct_change of each value to previous entry in group. GroupBy.pct_change(periods=1, fill_method='pad', limit=None, freq=None, axis=0) DataFrameGroupBy.pct_change(periods=1, fill_method='pad', limit=None, freq=None, axis=0)
GroupBy.size() Compute group sizes. GroupBy.size() DataFrameGroupBy.size()
GroupBy.sem() Compute standard error of the mean of groups, excluding missing values. GroupBy.sem(ddof=1)
GroupBy.std() Compute standard deviation of groups, excluding missing values. GroupBy.std(ddof=1)
GroupBy.sum([numeric_only, min_count]) Compute sum of group values. GroupBy.sum(numeric_only=True, min_count=0)
GroupBy.var([ddof]) Compute variance of groups, excluding missing values. GroupBy.var(ddof=1)
GroupBy.tail() 返回每组的最后n行,默认5行 GroupBy.tail(n=5)


了解更多 >> Pandas 用户指南:Group by: split-apply-combine Pandas 参考:GroupBy


时间序列

概览

Pandas把时间相关分为4种概念,用8个类来表示。

概念 描述 标量类 数组类 pandas数据类型 主要创建方法 示例
日期时间 支持时区的特定日期时间点。
类似Python标准库的datetime.datetime。
Timestamp DatetimeIndex datetime64[ns]
或 datetime64[ns, tz]
to_datetime
date_range
pd.to_datetime('2020-01-01')生成:Timestamp('2020-01-01 00:00:00')
时间增量 持续时间,即两个日期或时间的差值。
类似Python标准库的datetime.timedelta。
Timedelta TimedeltaIndex timedelta64[ns] to_timedelta
timedelta_range
时间跨度 由时间点及其关联的频率定义的时间跨度。 Period PeriodIndex period[freq] Period
period_range
日期偏移 日期增量 DateOffset None None DateOffset

了解更多 >> pandas 文档:用户指南 - 时间序列


合并

concat

append

merge

join

绘图

pandas绘图基于Matplotlib,pandas的DataFrame和Series都自带生成各类图表的plot方法,能够方便快速生成各种图表。

了解更多 >> pandas文档:用户指南 - 可视化


基本图形

折线图

plot方法默认生成的就是折线图。如prices是一个DataFrame的含有收盘价close列,绘制收盘价的折线图:

s = prices['close']
s.plot() 

#设置图片大小,使用figsize参数
s.plot(figsize=(20,10))

条形图

对于不连续标签,没有时间序列的数据,可以绘制条形图,使用以下两种方法:

  • 使用plot()函数,设置kind参数为‘bar’ or ‘barh’,
  • 使用plot.bar()函数,plot.barh()函数
df.plot(kind='bar')    #假设df为每天股票数据  
df.plot.bar()          
df.resample('A-DEC').mean().volume.plot(kind='bar')    #重采集每年成交量平均值,绘制条形图(volume为df的成交量列)

df.plot.bar(stacked=True)    #stacked=True表示堆积条形图
df.plot.barh(stacked=True)    #barh 表示水平条形图 </nowiki>

直方图

直方图使用plot.hist()方法绘制,一般为频数分布直方图,x轴分区间,y轴为频数。组数用参数bins控制,如分20组bins=20

df.volume.plot.hist()    #df股票数据中成交量volume的频数分布直方图。
df.plot.hist(alpha=0.5)    #alpha=0.5 表示柱形的透明度为0.5
df.plot.hist(stacked=True, bins=20)    #stacked=True表示堆积绘制,bins=20表示分20组。
df.plot.hist(orientation='horizontal')    #orientation='horizontal' 表示水平直方图
df.plot.hist(cumulative=True)    #表示累计直方图  

df['close'].diff().hist()    #收盘价上应用diff函数,再绘制直方图
df.hist(color='k', bins=50)     #DataFrame.hist函数将每列绘制在不同的子图形上。

箱型图

箱型图可以使用plot.box()函数或DataFrame的boxplot()绘制。 参数:

  • color,用来设置颜色,通过传入颜色字典,如color={'boxes': 'DarkGreen', 'whiskers': 'DarkOrange', 'medians': 'DarkBlue', 'caps': 'Gray'}
  • sym,用来设置异常值样式,如sym='r+'表示异常值用'红色+'表示。
df.plot.box()
df[['close','open', 'high']].plot.box()
#改变箱型颜色,通过传入颜色字典
color={'boxes': 'DarkGreen', 'whiskers': 'DarkOrange', 'medians': 'DarkBlue', 'caps': 'Gray'}
df.plot.box(color=color, sym='r+')    #sym用来设置异常值样式,'r+'表示'红色+'
df.plot.box(positions=[1, 4, 5, 6, 8])    #positions表示显示位置,df有5个列, 第一列显示在x轴1上,第二列显示在x轴4上,以此类推
df.plot.box(vert=False)    #表示绘制水平箱型图
df.boxplot()   

#绘制分层箱型图,通过设置by关键词创建分组,再按组,分别绘制箱型图。如下面例子,每列按A组,B组分别绘制箱型图。
df = pd.DataFrame(np.random.rand(10, 2), columns=['Col1', 'Col2'])
df['x'] = pd.Series(['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'])
df.boxplot(by='x')

#还可以再传入一个子分类,再进一步分组绘制。如:
df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y'])

散点图

散点图使用DataFrame.plot.scatter()方法绘制。通过参数x,y指定x轴和y轴的数据列。

df.plot.scatter(x='close', y='volume')    #假如df为每日股票数据,图表示收盘价与成交量的散点图

#将两组散点图绘制在一张图表上,重新ax参数如
ax = df.plot.scatter(x='close', y='volume', color='DarkBlue', label='Group 1')    #设置标签名label设置标名
df.plot.scatter(x='open', y='value', color='DarkGreen', label='Group 2', ax=ax)

#c参数表示圆点的颜色按按volume列大小来渐变表示。
df.plot.scatter(x='close', y='open', c='volume', s=50)    #s表示原点面积大小
df.plot.scatter(x='close', y='open', s=df['volume']/50000)  #圆点的大小也可以根据某列数值大小相应设置。

饼图

饼图使用DataFrame.plot.pie()或Series.plot.pie()绘制。如果数据中有空值,会自动使用0填充。

其他绘图函数

这些绘图函数来自pandas.plotting模块。

矩阵散点图(Scatter Matrix Plot)

矩阵散点图(Scatter Matrix Plot)使用scatter_matrix()方法绘制

from pandas.plotting import scatter_matrix     #使用前需要从模块中导入该函数
scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')    #假设df是每日股票数据,会每一列相对其他每一列生成一个散点图。

密度图(Density Plot)

密度图使用Series.plot.kde()和DataFrame.plot.kde()函数。

df.plot.kde()

安德鲁斯曲线(Andrews Curves)

安德鲁斯曲线

平行坐标图(Parallel Coordinates)

Lag plot

自相关图(Autocorrelation Plot)

自相关图

自举图(Bootstrap plot)

绘图格式

预设置图形样式

matplotlib 从1.5开始,可以预先设置样式,绘图前通过matplotlib.style.use(my_plot_style)。如matplotlib.style.use('ggplot') 定义ggplot-style plots.

样式参数

大多数绘图函数,可以通过一组参数来设置颜色。

标签设置

可通过设置legend参数为False来隐藏图片标签,如

df.plot(legend=False)

尺度

  • logy参数用来将y轴设置对数标尺
  • logx参数用来将x轴设置对数标尺
  • loglog参数用来将x轴和y轴设置对数标尺
ts.plot(logy=True)

双坐标图

两组序列同x轴,但y轴数据不同,可以通过第二个序列设置参数:secondary_y=True,来设置第二个y轴。

#比如想在收盘价图形上显示cci指标:
prices['close'].plot()
prices['cci'].plot(secondary_y=True)

#第二个坐标轴要显示多个,可以直接传入列名
ax = df.plot(secondary_y=['cci', 'RSI'], mark_right=False)    #右边轴数据标签默认会加个右边,设置mark_right为False取消显示
ax.set_ylabel('CD scale')     #设置左边y轴名称
ax.right_ax.set_ylabel('AB scale')    #设置右边y轴名称

子图

DataFrame的每一列可以绘制在不同的坐标轴(axis)中,使用subplots参数设置,例如:

df.plot(subplots=True, figsize=(6, 6))

子图布局

子图布局使用关键词layout设置,

输入输出

pandas的读取函数是顶层函数,如pandas.read_csv()一般返回一个pandas对象。写入函数是相应对象的方法,如DataFrame.to_csv()将DataFrame对象写入到csv文件。下表是可用的读取和写入函数。

数据描述 格式类型 读取函数 写入函数
CSV text read_csv to_csv
Fixed-Width Text File text read_fwf
JSON text read_json to_json
HTML text read_html to_html
Local clipboard text read_clipboard to_clipboard
MS Excel read_excel to_excel
OpenDocument binary read_excel
HDF5 Format binary read_hdf to_hdf
Feather Format binary read_feather to_feather
Parquet Format binary read_parquet to_parquet
ORC Format binary read_orc
Msgpack binary read_msgpack to_msgpack
Stata binary read_stata to_stata
SAS binary read_sas
SPSS binary read_spss
Python Pickle Format binary read_pickle to_pickle
SQL SQL read_sql to_sql
Google BigQuery SQL read_gbq to_gbq

资源

官网

相关网站

书籍

《利用Python进行数据分析 第2版》 - Wes McKinney

参考文献