Python 数据分析 Numpy、Pandas、Matplotlib、Seaborn 常见用法

一、前言

Python 机器学习必用到
正是这些功能强大的数据分析库,才使 Python 在人工智能领域立于不败之地
如:
2018 Kaggle 全球机器学习算法竞赛,官方提供的训练数据,就几张 Excel 表,
Python 使用 Pandas,一句代码即可完整读取
而 Java 方面使用第三方包 POI 的方式,相形见绌

二、示例代码

1.Numpy

import numpy as np  # 一般 numpy 采用 np 简写

# numpy 主要为机器学习提供矩阵运算

# 1、创建
# 1.1 最简单
a = np.array([2, 23, 4])
print("1.1\n", a)
# 1.2 指定类型,TensorFlow 一般为 float32
a = np.array([2, 23, 4], dtype=np.float32)
print("1.2\n", a)
# 1.3 特定数据
a = np.zeros((3, 4))  # 数据全为0,3 行4 列
print("1.3\n", a)
a = np.array([[3, 4, 5], [5, 12, 13]])  # 2d 矩阵 2 行 3 列
print("1.4\n", a)
a = np.arange(1, 10, 2)  # 1-10 的数据,2步长 [1 3 5 7 9]
print("1.5\n", a)
a = np.linspace(0, 10, 6)  # 开始端1,结束端10,且分割成5个数据,生成线段  [ 0.  2.  4.  6.  8. 10.]
print("1.6\n", a)

# 2、属性
nums = np.arange(12).reshape(3, 4)  # reshape 改变数据的形状
print("2\n", nums)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
print('2.1 维度:', nums.ndim)  # 2
print('2.2 行数,列数 :', nums.shape)  # (2, 3)
print('2.3 元素个数:', nums.size)  # 6

# 3、运算
a = np.array([10, 20, 30, 40])  # array([10, 20, 30, 40])
b = np.arange(4)  # array([0, 1, 2, 3])
# 3.1 +
c = a + b  # array([10, 21, 32, 43])
print("3.1\n", c)
# 3.2 -
c = a - b  # array([10, 19, 28, 37])
print("3.2\n", c)
# 3.3 *
c = a * b  # array([  0,  20,  60, 120])
print("3.3\n", c)
# 3.4 三角函数
c = np.sin(5) ** 2 + np.cos(5) ** 2  # sina^2 +cosb^2=1
print(c)
# 3.5 随机矩阵
a = np.random.random((2, 4))  # 每一元素均是来自从0 到1 的随机数
print(a)
# 3.6 标准的矩阵乘法运算
a = np.array([10, 20, 30, 40])  # array([10, 20, 30, 40])
b = np.arange(4)  # array([0, 1, 2, 3])
c_dot = np.dot(a, b)
print(c_dot)  # 200
c_dot_2 = a.dot(b)
print(c_dot_2)  # 200
# 3.7 sum()、max()、min()
a = np.arange(12).reshape(3, 4)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
print(a)
print("sum\n", np.sum(a))  # 66(所有元素和)
print("max\n", np.max(a))  # 11(所有元素最大值)
print("min\n", np.min(a))  # 0(所有元素最小值)
# axis=1 为每一行,axis=0 为每一列
print("sum =", np.sum(a, axis=1))  # 每一行之和 [ 6 22 38]
print("min =", np.min(a, axis=0))  # 每一列最小 [0 1 2 3]
print("max =", np.max(a, axis=1))  # 每一行最大 [ 3  7 11]
# 3.8 运算其他用法
A = np.arange(12).reshape(3, 4)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# 3.8.1 索引
print(A)
print(np.argmin(A))  # 最小元素 0 索引0
print(np.argmax(A))  # 最大元素 12 索引11
print("3.8.1.A[1][1]\n", A[1][1])  # 5
print("3.8.1.根据索引切片\n", A[1, 1:3])  # 根据索引切片 [5 6]
# 3.8.2 最大最小界限
print("3.8.2 最大最小界限\n", np.clip(A, 5, 9))
# [[5 5 5 5]
#  [5 5 6 7]
#  [8 9 9 9]]
# 3.8.3 排序
print("3.8.3 排序\n", np.sort(A))
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# 3.8.4 矩阵的转置(下面两种用法一样)
print("3.8.4 矩阵的转置1\n", np.transpose(A))
print("3.8.4 矩阵的转置2\n", A.T)
# [[ 0  4  8]
#  [ 1  5  9]
#  [ 2  6 10]
#  [ 3  7 11]]

# 4、合并
A = np.array([1, 1, 1])
B = np.array([2, 2, 2])
# 4.1 上下合并
print("4.1 左右合并\n", np.vstack((A, B)))
# [[1 1 1]
#  [2 2 2]]
# 4.2 左右合并
print("4.2 上下合并\n", np.hstack((A, B)))
# [1 1 1 2 2 2]

# 5、分割
A = np.arange(12).reshape((3, 4))
# 5.1 横向分割
print(np.vsplit(A, 3))  # 等于 print(np.split(A, 3, axis=0))
# [array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8,  9, 10, 11]])]
# 5.2 纵向分割
print(np.hsplit(A, 2))  # 等于 print(np.split(A, 2, axis=1))
# [array([[0, 1],
#        [4, 5],
#        [8, 9]]), array([[ 2,  3],
#        [ 6,  7],
#        [10, 11]])]

2.Pandas

import pandas as pd
import numpy as np

# pandas 经常结合 numpy 一起使用

# 1 pandas 数据结构
# 1.1 序列Series
s = pd.Series([1, 2, 3, np.nan, 4.5, 10])
print(s)
# 0     1.0
# 1     2.0
# 2     3.0
# 3     NaN
# 4     4.5
# 5    10.0
# dtype: float64
# 1.2 表格 DataFrame
dates = pd.date_range('20180723', periods=3)  # periods = 行数
df1 = pd.DataFrame(np.arange(12).reshape((3, 4)), index=dates)
print(df1)
#             0  1   2   3
# 2018-07-23  0  1   2   3
# 2018-07-24  4  5   6   7
# 2018-07-25  8  9  10  11
df2 = pd.DataFrame({'A': 1.,
                    'B': pd.Timestamp('20180723'),
                    'C': pd.Series(1, index=list(range(4)), dtype='float32'),
                    'D': np.array([3] * 4, dtype='int32'),
                    'E': pd.Categorical(["a", "b", "c", "d"]),
                    'F': 'cun'})
print(df2)
#      A          B    C  D  E    F
# 0  1.0 2018-07-23  1.0  3  a  cun
# 1  1.0 2018-07-23  1.0  3  b  cun
# 2  1.0 2018-07-23  1.0  3  c  cun
# 3  1.0 2018-07-23  1.0  3  d  cun

# 2 数据选择
# 2.1 行、列
print(df2['E'])
print(df2.E)
# Name: E, dtype: category
# Categories (4, object): [a, b, c, d]
# 0    a
# 1    b
# 2    c
# 3    d
# Name: E, dtype: category
# Categories (4, object): [a, b, c, d]
# 2.2 标签 loc
print(df2.loc[:, ['B', 'C']])
#            B    C
# 0 2018-07-23  1.0
# 1 2018-07-23  1.0
# 2 2018-07-23  1.0
# 3 2018-07-23  1.0
# 2.3 序列 iloc
print(df2.iloc[1, 4])  # 行、列
# b
print(df2.iloc[[1, 3], 2:5])  # 指定、切片
#      C  D  E
# 1  1.0  3  b
# 3  1.0  3  d
# 2.4 ix(序列 + 标签)
print(df2.ix[1:2, ['B', 'E']])
#            B  E
# 1 2018-07-23  b
# 2 2018-07-23  c
# 2.5 判断
print(df2[df2['E'] == 'b'])
#      A          B    C  D  E    F
# 1  1.0 2018-07-23  1.0  3  b  cun

# 3 修改数据
df2.iloc[1, 2] = np.nan
df2.iloc[2, 3] = np.nan
print(df2)
#      A          B    C    D  E    F
# 0  1.0 2018-07-23  1.0  3.0  a  cun
# 1  1.0 2018-07-23  NaN  3.0  b  cun
# 2  1.0 2018-07-23  1.0  NaN  c  cun
# 3  1.0 2018-07-23  1.0  3.0  d  cun

# 4 处理 NaN 数据
# 4.1 dropna 去掉含 NaN 的行、列
dates = pd.date_range('20180723', periods=3)
df = pd.DataFrame(np.arange(12).reshape((3, 4)), index=dates, columns=['A', 'B', 'C', 'D'])
df.iloc[0, 1] = np.nan
df.iloc[1, 2] = np.nan
print(df)
# 2018-07-23  0  NaN   2.0   3
# 2018-07-24  4  5.0   NaN   7
# 2018-07-25  8  9.0  10.0  11
print(df.dropna(
    axis=0,  # 0: 对行进行操作; 1: 对列进行操作
    how='any'  # 'any': 只要存在 NaN 就 drop 掉; 'all': 必须全部是 NaN 才 drop
))  # how={'any', 'all'}
# 2018-07-25  8  9.0  10.0  11
print(df.fillna(value=666))  # 修改值
# 2018-07-23  0  666.0    2.0   3
# 2018-07-24  4    5.0  666.0   7
# 2018-07-25  8    9.0   10.0  11
print(pd.isnull(df))  # True 表示缺失数据
# 2018-07-23  False   True  False  False
# 2018-07-24  False  False   True  False
# 2018-07-25  False  False  False  False

# 5 Excel 等导入导出
# 读取csv
data = pd.read_excel("test.xlsx")  # 先 pip3 install xlrd
# 打印出data
print(data)
#    id       name  score
# 0  11  likeqiang     98
# 1  22  xijinping     99
# 2  33  wenjiabao    100
# 保存
data.to_pickle('student.pickle')

5 Excel 等导入导出
Excel 数据
这里写图片描述
保存的文件
这里写图片描述

3.Matplotlib

import matplotlib.pyplot as plt
import numpy as np

# Matplotlib 主要作用为可视化数据

# 1 线长
x = np.linspace(-1, 3, 50)
y = x ** 2 + 1

# 2 窗口:num 编号、figsize 大小
plt.figure(num=3, figsize=(8, 5))

# 线:xy 轴、color 颜色、linewidth 宽度、linestyle 风格、label 线名
plt.plot(x, y, color='red', linewidth=2.5, linestyle='--', label='$y=x^2+1$')

# 3 轴名
# 3.1 x
plt.xlabel('I am x')
# 3.2 y
plt.ylabel('I am y')

# 4 轴刻度
# 4.1 y
plt.yticks([-1, 0, 1, 2, 3], [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
# 4.2 x
new_ticks = np.linspace(-1, 3, 10)
plt.xticks(new_ticks)

# 5 坐标范围
# 5.1 x
plt.xlim((-1, 3))
# 5.2 y
plt.ylim((-1, 3))

# 6 表框
ax = plt.gca()
# 右
ax.spines['right'].set_color('none')
# 上
ax.spines['top'].set_color('none')

# 7 刻度位置
# 7.1 x
ax.xaxis.set_ticks_position('bottom')
# 7.2 y
ax.yaxis.set_ticks_position('left')

# 8 原点
# 8.1 y=0
ax.spines['bottom'].set_position(('data', 0))
# 8.2 x=0
ax.spines['left'].set_position(('data', 0))

# 9 显示图例(+ 线名)
plt.legend(loc='upper right')  # upper right 右上角
#   best
#   upper right
#   upper left
#   lower left
#   lower right
#   right
#   center left
#   center right
#   lower center
#   upper center
#   center

# 10 标注
# 10.1 注释
plt.text(1, 2, r'$\ \ \ (1,1)$',
         fontdict={'size': 16, 'color': 'g'})
# 10.2 做点垂线
x0 = 1
y0 = x0 ** 2 + 1
plt.plot([x0, x0, ], [0, y0, ], 'y--', linewidth=1.0)
# 10.3 点:s 颜色、color 颜色
plt.scatter([x0, ], [y0, ], s=50, color='g')
# 10.4 箭头
plt.annotate(r'$y=x^2+1$', xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=10,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))

# 10.5 刻度背景
for label in ax.get_xticklabels() + ax.get_yticklabels():
    # facecolor 前景颜色、edgecolor 边框颜色\alpha 透明度
    label.set_bbox(dict(facecolor='yellow', edgecolor='green', alpha=0.1))

plt.show()

这里写图片描述

4.seaborn

已有文章总结得很好了
Python数据可视化-seaborn
python可视化:关于seaborn的应用

# Matplotlib仍然是Seaborn的基础,这意味着结构仍然是一样的,您需要使用plt.show()使图像显示给您

# Import the necessary libraries
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

# 定义数值 N
N = 500

# 创建颜色表
current_palette = sns.color_palette("muted", n_colors=5)
cmap = ListedColormap(sns.color_palette(current_palette).as_hex())

# 初始化数据
data1 = np.random.randn(N)
data2 = np.random.randn(N)

# 这里设置 5 种颜色
colors = np.random.randint(0, 5, N)

# 创建 scatter 类型
plt.scatter(data1, data2, c=colors, cmap=cmap)

# 添加颜色
plt.colorbar()

# 显示
plt.show()

这里写图片描述

三、其他

有空更新完善代码,使之更加全面,实用
参考资料:莫烦Python

猜你喜欢

转载自blog.csdn.net/larger5/article/details/81176130