0%

Pandas 库

1、安装

pandas是第三方库需要手动安装

1
2
3
4
5
# 使用pip安装
pip3 install pandas

# Linux安装
sudo apt-get install python3-pandas

2、数据类型

Pandas 的数据类型主要有以下几种,它们分别是:Series(一维数组),DataFrame(二维数组),Panel(三维数组),Panel4D(四维数组),PanelND(更多维数组)。

1、Series

SeriesPandas 中最基本的一维数组形式。其可以储存整数、浮点数、字符串等类型的数据。索引是 Pandas 数据结构中的一大特性,它主要的功能是帮助我们更快速地定位数据。

1
2
3
4
5
6
7
# pandas.Series(data=None, index=None)
# data 可以是字典,或者NumPy 里的 ndarray 对象等
# index 是数据索引
s = pd.Series({'a': 10, 'b': 20, 'c': 30})
s = pd.Series(np.random.randn(5))
print(s)
print(type(s))

2、DataFrame

DataFramePandas 中最为常见、最重要且使用频率最高的数据结构。DataFrame 和平常的电子表格或 SQL 表结构相似。你可以把 DataFrame 看成是 Series 的扩展类型,它仿佛是由多个 Series 拼合而成。它和 Series 的直观区别在于,数据不但具有行索引,且具有列索引。

ataFrame 可以由以下多个类型的数据构建:

  • 一维数组、列表、字典或者 Series 字典。
  • 二维或者结构化的 numpy.ndarray
  • 一个 Series 或者另一个 DataFrame。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# pandas.DataFrame(data=None, index=None, columns=None)
# data 数据
# index 数据索引
# columns 列索引
df = pd.DataFrame({'one': pd.Series([1, 2, 3]),
'two': pd.Series([4, 5, 6])})
df = pd.DataFrame({'one': [1, 2, 3], 'two': [4, 5, 6]})
df = pd.DataFrame([{'one': 1, 'two': 4},
{'one': 2, 'two': 5},
{'one': 3, 'two': 6}])
df = pd.DataFrame(np.random.randint(5, size=(2, 4)))
print(df)
print(type(df))

# Series 和 DataFrame 对比
s = pd.Series(np.random.randint(5, size=(5,)))
df = pd.DataFrame(np.random.randint(5, size=(5,)))
print(s)
print(df)

3、数据读取

官方参考文档

通过调用以pandas.read_为前缀的方法可以读取相应的数据文件,且支持连接数据库。

读取CSV文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
df: pd.core.frame.DataFrame = pd.read_csv(
"https://labfile.oss.aliyuncs.com/courses/906/los_census.csv")
print(type(df))

# 默认输出前5条数据
print(df.head())

# 指定显示后7条数据
print(df.tail(7))

# describe() 相当于对数据集进行概览,会输出该数据集每一列数据的计数、最大值、最小值等。
print(df.describe())

# 将 DataFrame 转换为 NumPy数组
print(df.values)

# 查看索引
print(df.index)

# 查看列名
print(df.columns)

# 查看形状
print(df.shape)

4、数据选择

基于索引数字选择

1
2
3
4
5
6
7
8
9
10
11
12
13
14
df: pd.core.frame.DataFrame = pd.DataFrame(np.random.randint(5, size=(4, 5)))
# print(df)

# 选择第3行
print(df.iloc[3])

# 选择前3行
print(df.iloc[:3])

# 选择 1, 3 行
print(df.iloc[[1, 3]])

# 选择 1-3列
print(df.iloc[:, 1:4])

基于标签名称选择

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
lst = np.arange(9).reshape(3, 3)
df = pd.DataFrame(lst, index=['r1', 'r2', 'r3'], columns=['c1', 'c2', 'c3'])
# print(df)

# df.loc[] 与 df.iloc[] 用法相似
# 选择第3行
print(df.loc['r3'])

# 选择前3行
print(df.loc[:'r3'])

# 选择1,3行
print(df.loc[['r1', 'r3']])

# print(df.loc['r2':'r3', 'c1':'c2'])

5、数据删除和填充

1、数据删除

Pandas 中,以 .drop 开头的方法都与数据删减有关。

DataFrame.drop可以直接去掉数据集中指定的列和行。

1
2
3
4
5
6
7
8
9
lst = np.arange(9).reshape(3, 3)
df = pd.DataFrame(lst, index=['r1', 'r2', 'r3'], columns=['c1', 'c2', 'c3'])

# df.drop(labels=[], axis=1, inplace=True)
# labels: 要删除的行或列的标签或索引
# axis: [0,1] 0表示按行删除,1表示按列删除
# inplace: 值为'True'则在原数据上修改,为'False'则返回数据的copy
df.drop(['r1', 'r3'], 0, inplace=True)
print(df)

DataFrame.drop_duplicates可以删除数据中重复的列

1
2
3
4
5
6
7
8
9
10
11
12
lst = np.random.randint(5, size=(3, 3))
df = pd.DataFrame(lst, index=['r1', 'r2', 'r3'], columns=['c1', 'c2', 'c3'])

# df.drop_duplicates(subset=None, keep='first, inplace=True)
# subset: 列的标签的一个子集,表示只考虑某些列;None表示考虑所有列
# keep: {'first', 'last', False}
# 'first' 表示保留第一次出现
# 'last' 表示最后一次出现
# False 表示全都删除
# inplace: 值为'True'则在原数据上修改,为'False'则返回数据的copy
df.drop_duplicates(subset=['c1', 'c3'], inplace=True)
print(df)

DataFrame.dropna删除数据集中空缺的数据列或行

1
2
3
4
5
6
7
8
9
10
11
12
lst = [[0, 1, 2], [3, 4], [6]]
df = pd.DataFrame(lst, index=['r1', 'r2', 'r3'], columns=['c1', 'c2', 'c3'])
# print(df)

# df.dropna(axis, how='any', thresh=None, subset, inplace)
# axis: [0,1] 0表示按行删除,1表示按列删除
# how: {'any', 'all'} 'any'只要有一个数据为空;'all'需要整行或整列的数据为空
# thresh: int value , 表示保留下来的行或列只是有多少个非空数据
# subset: 列的标签的一个子集,表示只考虑某些列;None表示考虑所有列
# inplace: 值为'True'则在原数据上修改,为'False'则返回数据的copy
df.dropna(axis=1, thresh=3, inplace=True)
print(df)

2、数据填充

Pandas的缺失值由NaNNaT,前者表示‘这不是一个数字’,后者表示‘这不是一个时间戳’。

1、缺失值检测
1
2
3
4
5
6
7
lst = [[0, 1, 2], [3, 4], [6]]
df = pd.DataFrame(lst, index=['r1', 'r2', 'r3'], columns=['c1', 'c2', 'c3'])
print(df)
# df.isna() 返回df中的每个数据是否为空,若为空则值为True
print(df.isna())
# df.notna() 返回df中的每个数据是否为空,若为空则值为False
print(df.notna())
2、填充缺失值

1、使用fillna()进行填充

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
lst = [[0, 1, 2], [3, 4], [6], [9, 10, 11]]
df = pd.DataFrame(lst, index=['r1', 'r2', 'r3',
'r4'], columns=['c1', 'c2', 'c3'])
print(df)

# df.fillna(value)
# value: 使用value来填充NaN
df = df.fillna(value=0)
print(df)

# df.fillna(method='pad', asix=0,limit)
# method: {'pad', 'bfill'}填充方法
# 'pad':使用前面的值进行填充
# 'bfill': 使用后面的值进行填充
# axis: [0,1] 0表示按行删除,1表示按列删除
# limit: 限制连续填充的数量
df = df.fillna(method='pad', axis=1, limit=1)
print(df)

# 使用Series数据填充对应的列
# 使用平均值填充'c1','c2'和'c3'
df = df.fillna(df.mean()['c1': 'c3'])
print(df)
# 使用平均值填充'c1'和'c3'列
df = df.fillna(df.mean()[['c1', 'c3']])
print(df)

2、插值填充

使用interpolate()进行线性插值

1
2
3
4
5
6
7
8
9
10
11
12
df = pd.DataFrame({'A': [1.1, 2.2, np.nan, 4.5, 5.7, 6.9],
'B': [.21, np.nan, np.nan, 3.1, 11.7, 13.2]})
print(df)
# 线性插值
df = df.interpolate()
# 二次插值
df = df.interpolate(method='quadratic')
# 累计分布
df = df.interpolate(method='pchip')
# 平滑绘图
df = df.interpolate(method='akima')
print(df)

6、数据可视化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt


df = pd.DataFrame({'A': [1.1, 2.2, np.nan, 4.5, 5.7, 6.9],
'B': [.21, np.nan, np.nan, 3.1, 11.7, 13.2]})
# print(df)

# 平滑绘图
df = df.interpolate(method='akima')
# 绘制图像
df.plot()
plt.show()

0、参考

官网

Pandas 中文

Pandas 数据处理基础课程