numpyの、matplotlibの、パンダ

numpyのモジュール

numpyの概要

numpyの公式文書:https://docs.scipy.org/doc/numpy/reference/?v=20190307135750

numpyの数値Pythonは拡張子を計算するオープンソースです。このようなライブラリーは、Python、ネストされたリスト構造自体がはるかに効率的(構造はnumpyの配列を表すために使用されてもよい)であるよりも、大きいnumpyの配列を格納し、処理するために使用することができます。

numpyのライブラリには2つの機能があります。

  1. リストのリストから別の、運用、配列操作だけでなく、統計的分布との単純な数学モデルの配列を提供しています
  2. 建てによる簡単な操作に計算速度は、さえパイソン、それは依存関係のパンダ、sklearn均一になるように。高度なフレームワークなどTensorFlow、PyTorchのような、ともnumpyの配列操作は非常に似ています。

numpyの使用

import numpy as np

lt1 = [1,2,3]
lt2 = [4,5,6]
arry1 = np.array(lt1)
arry2 = np.array(lt2)
print(arry1*arry2)    # [ 4 10 18]  

numpyの配列を作成します。

# 一维数组
arr1 = np.array([1,2,4])
print(type(arr1), arr1)  # <class 'numpy.ndarray'> [1 2 4]

# 二维数组
arr = np.array([
    [1,2,3],
    [4,5,6]
])

print(arr)  
'''
[[1 2 3]
 [4 5 6]]
'''


# 三维数组
arr = np.array([
    [[1, 2, 3],
     [4, 5, 6]],
    [[1, 2, 3],
     [4, 5, 6]]
])

print(arr)
'''
[[[1 2 3]
  [4 5 6]]

 [[1 2 3]
  [4 5 6]]]
'''

共通属性の配列numpyの

プロパティ 説明
T (高次元配列の点で)アレイの転置
DTYPE 配列要素のデータ型
サイズ 配列要素の数
DECISION 配列の次元
形状 (タプルの形式で)アレイの寸法サイズ
astype 型変換

DTYPEデータ型の配列要素は、アレイは、Pythonのインタープリターをnumpyの属し、INT32 /のfloat64属するnumpyの

# 转置
arr = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print(f'arr的转置为\n{arr.T}')
'''
arr的转置为
[[1 4]
 [2 5]
 [3 6]]
'''

# dtype数据类型
arr = np.array([
    [1., 2., 3.],
    [4, 5, 6]
])

print(arr.dtype)  # float64


# 数组元素的个数
print(arr.size)   # 6

# 数组的维数
print(arr.ndim)  # 2

# 数组的维度大小(以元组形式, 几行几列)
print(arr.shape)  # (2,3)

# 数组类型转换
arr = np.array([
    [1, 2, 3],
    [4, 5, 6]
])
res = arr.astype(np.float64)
print(res) 
'''
[[1. 2. 3.]
 [4. 5. 6.]]
'''

numpyの配列を切断

切断のグループリストと同様切断スコア、切断は、切断の行と列のnumpyの配列を含みます

arr = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

print(arr[:,:])  # 行;列  取整个数组
print(arr[0,0])  # 取第一行第一列,1
print(arr[0,:])  # 取第一行  [1 2 3]
print(arr[:,2:])  # 取第三列 
'''
[[3]
 [6]]
'''

割り当て

arr = np.array([
    [1, 2, 3],
    [4, 5, 6]
])
arr[0,0] = 0
print(arr)   # 将二维数组第一行第一列元素赋值为0

arr[:,:] = 0
print(arr)  # 全部换为0
'''
[[0 0 0]
 [0 0 0]]
'''

人民元と組み合わせ

# 水平合并
arr1 = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

arr2 = np.array([
    [7, 8, 9],
    ['a', 'b', 'c']
])

print(np.hstack((arr1,arr2))) # 只能放元组
'''
[['1' '2' '3' '7' '8' '9']
 ['4' '5' '6' 'a' 'b' 'c']]
'''

# 垂直合并
print(np.vstack((arr1, arr2)))
'''
[['1' '2' '3']
 ['4' '5' '6']
 ['7' '8' '9']
 ['a' 'b' 'c']]
'''

print(np.concatenate((arr1, arr2)))  # 默认以列合并
'''
[['1' '2' '3']
 ['4' '5' '6']
 ['7' '8' '9']
 ['a' 'b' 'c']]
'''
print(np.concatenate((arr1, arr2), axis=1)) # 以行合并
'''
[['1' '2' '3' '7' '8' '9']
 ['4' '5' '6' 'a' 'b' 'c']]
'''

関数で配列を作成します。

方法 詳しいです
アレイ() 配列リストの変換、明示的に指定DTYPEを選択
arange() numpyのバージョンの範囲、浮動小数点数のサポート
linspace() 同様arange()、3番目のパラメータは、配列の長さであります
ゼロ() 所定の形状とDTYPEに基づいて、すべて0アレイを作成します
もの() 1指定された形状とDTYPEの完全なアレイを作成します
眼() マトリックスの作成
空の() ランダム要素の完全な配列を作成します
再形成() リシェイプ

もの/ゼロ/目/空

# ones
print(np.ones((2,3)))  # 构建两行三列的1
'''
[[1. 1. 1.]
 [1. 1. 1.]]
'''

# zeros
print(np.zeros((2,3)))  # 创建2行3列的0
'''
[[0. 0. 0.]
 [0. 0. 0.]]
'''

# eye
print(np.eye(3,3))  # 创建单位矩阵
'''
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
'''

# empty
print(np.empty((2,2)))  # 创建一个2行2列的数组,里面的元素是随机生成的
'''
[[1.42419938e-306 9.34609790e-307]
 [1.29060871e-306 7.56601165e-307]]
'''

linspace /ログ・スペース

print(np.linspace(1,100,10)) # 创建一个等差数列,1-100,有10个数
# [  1.  12.  23.  34.  45.  56.  67.  78.  89. 100.]

print(np.logspace(1,10,5))  # 创建等比数列、
# [1.00000000e+01 1.77827941e+03 3.16227766e+05 5.62341325e+07 1.00000000e+10]

アレンジ

print(np.arange(2,10))
# [2 3 4 5 6 7 8 9]

print(np.arange(2,10,2))  # 2-10,步长为2的数组
# [2 4 6 8]

形状復元を再構築

arr = np.ones([2,2])  # 本来是2*2的1
# print(arr) 
print(arr.reshape(1,4))  # 变成1*4的1
# [[1. 1. 1. 1.]]

配列の操作

演算子 説明
+ 2つの配列の対応する要素を追加するnumpyの
- 配列numpyの二減算対応する要素
* 2つの配列の対応する要素を乗算numpyの
/ テイクは整数業者であればnumpyのアレイ素子は、2つの分割に対応します
2つの配列のnumpyの対応する要素は、除算後の余りを取ります
** n個 各個々の配列要素は、2 **として、numpyのn乗を取る:各要素を二乗します
arr = np.array([
    [3, 4, 56],
    [12, 4, 25]
])
print(arr / 2)
'''
[[ 1.5  2.  28. ]
 [ 6.   2.  12.5]]
'''

arr = np.array([
    [3, 4, 56],
    [12, 4, 25]
])
print(arr ** 2)
'''
[[   9   16 3136]
 [ 144   16  625]]
'''

アレイ機能操作numpyの

numpyの配列関数 詳しいです
np.sin(ARR) 正弦、SIN(X)SIN(X)ARR取ら各要素のnumpyのアレイ
np.cos(ARR) 余弦ARR取ら各要素のnumpyのアレイ、COS(X)COS(X)
np.tan(ARR) numpyの正接ARR取ら各要素の配列、日焼け(x)は、黄褐色(X)
np.arcsin(ARR) アークサインARR取ら各要素のnumpyのアレイ、アークサイン(x)は、アークサイン(x)は
np.arccos(ARR) 逆余弦をとる各要素のARR numpyのアレイ、ARCCOS(X)ARCCOS(X)
np.arctan(ARR) 逆正接をとる各要素のARR numpyのアレイ、アークタンジェント(x)の逆正接(X)
np.exp(ARR) 指数関数ARR取ら各要素のnumpyのアレイ、exex
np.sqrt(ARR) ARR x-- \各要素の平方根のnumpyのアレイ(\ SQRT [2]} X {\)
arr = np.array([
    [3, 4, 56],
    [12, 4, 25]
])
print(np.sin(arr))
'''
[[ 0.14112001 -0.7568025  -0.521551  ]
 [-0.53657292 -0.7568025  -0.13235175]]
'''

numpy.randomは、乱数を生成し、

関数名 機能機能 パラメータ説明
ランド(D0、D1、⋯、dnd0、D1、⋯、DN) これは、一様に分布乱数を生成し、 n次元データの次元としてdndn
関数randn(D0、D1、⋯、dnd0、D1、⋯、DN) 標準正規乱数を生成します n次元データの次元としてdndn
randint(低[高、サイズ、DTYPE]) ランダムな整数を生成します 低:最小値;高:最大;サイズ:データの数
random_sample([サイズ]) 〔0,1)[0,1)で乱数を発生させます サイズは、ランダム形状の数である、またはタプルのリストであってもよいです
選択肢([サイズ]) ARRからランダム選択データ 一次元配列ARR;サイズのアレイ状
uniform(low,high [,size]) 给定形状产生随机数组 low为最小值;high为最大值,size为数组形状
shuffle(a) 与random.shuffle相同 a为指定数组

matplotlib模块

条形图

初始的:

from matplotlib import pyplot as plt

classes = ['3班', '4班', '5班', '6班']
students = [55, 45, 60, 50]

plt.bar(classes, students)
plt.show()

from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties  # 修改字体

font = FontProperties(fname='C:\Windows\Fonts\simkai.ttf')  # 中文字体


classes = ['3班', '4班', '5班', '6班']
students = [55, 45, 60, 50]
classes_index = range(len(classes))

plt.bar(classes_index, students)
plt.xticks(classes_index, classes, FontProperties=font)

plt.show()

from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties  # 修改字体

font = FontProperties(fname='C:\Windows\Fonts\simkai.ttf')  # 中文字体

plt.style.use('ggplot')  # 设置背景条纹

classes = ['3班', '4班', '5班', '6班']
students = [55, 45, 60, 50]
classes_index = range(len(classes))

plt.bar(classes_index, students, color='darkblue')

plt.xlabel('学生', FontProperties=font)
plt.ylabel('学生人数', FontProperties=font)
plt.title('班级-学生人数', FontProperties=font, fontsize=20, fontweight=25)
plt.xticks(classes_index, classes, FontProperties=font)  # 将x轴坐标替换成classes

plt.show()

直方图

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties  # 修改字体

font = FontProperties(fname='C:\Windows\Fonts\simkai.ttf')  # 中文字体

# 修改背景为条纹
plt.style.use('ggplot')

x1 = np.random.randn(10000)  # 随机生成符合正太分布的数
x2 = np.random.randn(10000)

plt.hist(x1, bins=50, color='darkgreen')  # bins=50表示每个变量的值分成50份,即会有50根柱子
plt.show()

# 直方图
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties  # 修改字体

font = FontProperties(fname='C:\Windows\Fonts\simkai.ttf')  # 中文字体

# 修改背景为条纹
plt.style.use('ggplot')

x1 = np.random.randn(10000)  # 随机生成符合正太分布的数
x2 = np.random.randn(10000)

fig = plt.figure()  # 生成一张画布
ax1 = fig.add_subplot(1,2,1) # 一行两列取第一个
ax2 = fig.add_subplot(1,2,2) # 一行两列取第二个

ax1.hist(x1, bins=50, color='darkgreen')  # bins=50表示每个变量的值分成50份,即会有50根柱子
ax2.hist(x2, bins=50, color='red')

# 大标题
fig.suptitle('两个正太分布', FontProperties=font)

# 添加子标题
ax1.set_title('x1的正态分布', FontProperties=font)
ax2.set_title('x2的正态分布', FontProperties=font)
plt.show()

折线图

# 折线图
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties  # 修改字体

font = FontProperties(fname='C:\Windows\Fonts\simkai.ttf')  # 中文字体

# 修改背景为条纹
plt.style.use('ggplot')

np.random.seed(1)
# 使用numpy的累加和,保证数据取值范围不会在(0,1)内波动
x1 = np.random.randn(40).cumsum()
x2 = np.random.randn(40).cumsum()
x3 = np.random.randn(40).cumsum()
x4 = np.random.randn(40).cumsum()

plt.plot(x1, color='red', marker='o', linestyle='-', label='红实线')
plt.plot(x2, color='yellow', marker='x', linestyle='--', label='黄虚线')
plt.plot(x3, color='blue', marker='*', linestyle='-.', label='蓝点线')
plt.plot(x4, color='black', marker='s', linestyle=':', label='绿点图')

# loc='best'给label自动选择最好的位置
plt.legend(loc='best', prop=font)
plt.show()

散点图+直线图

# 散点图
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties  # 修改字体
font = FontProperties(fname='C:\Windows\Fonts\simkai.ttf')

plt.style.use('ggplot')

# fig = plt.figure(figsize=(10,20)) # 控制画布大小
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

x1 = np.arange(20)
y1 = x1 ** 2

x2 = np.arange(20)
y2 = x2


ax1.scatter(x1, y1, color='red', label='红')
ax1.scatter(x2, y2, color='blue', label='蓝')
ax2.plot(x1,y1)
ax2.plot(x2,y2)

fig.suptitle('两张图', FontProperties=font)
ax1.set_title('散点图', FontProperties=font)
ax2.set_title('折线图', FontProperties=font)
ax1.legend(prop=font)
plt.show()

pandas模块

pandas中有两个主要的数据结构,其中Series数据结构类似于Numpy中的一维数组,DataFrame类似于多维表格数据结构。

pandas是python数据分析的核心模块。它主要提供了五大功能:

  1. 支持文件存取操作,支持数据库(sql)、html、json、pickle、csv(txt、excel)、sas、stata、hdf等。
  2. 支持增删改查、切片、高阶函数、分组聚合等单表操作,以及和dict、list的互相转换。
  3. 支持多表拼接合并操作。
  4. 支持简单的绘图操作。
  5. 支持简单的统计分析操作。
import pandas as pd
index = pd.date_range('2019-01-01', periods=6, freq='M')
print(index)

'''
DatetimeIndex(['2019-01-31', '2019-02-28', '2019-03-31', '2019-04-30',
               '2019-05-31', '2019-06-30'],
              dtype='datetime64[ns]', freq='M')
'''
import numpy as np
import pandas as pd

index = pd.date_range('2019-01-01', periods=6, freq='M')
columns = ['c1','c2','c3','c4']
# print(columns)
val = np.random.randn(6, 4)
# print(val)

df = pd.DataFrame(index=index, columns=columns, data=val)

# 保存文件,读出文件
df.to_excel('data.xls')

# 读出文件
df = pd.read_excel('data.xls', index_col=[0])
print(df)

'''
                  c1        c2        c3        c4
2019-01-31 -1.469848 -0.875899 -0.571439  0.274287
2019-02-28  0.783315 -0.333277  0.091470  1.484056
2019-03-31  0.611354  0.565803 -1.298068  0.666117
2019-04-30 -0.892975 -0.144261 -2.596248  1.103916
2019-05-31 -1.207643 -0.475502 -1.577926 -0.373518
2019-06-30 -0.233937 -1.492533 -0.207368  0.163620

'''

print(df.index)
'''
DatetimeIndex(['2019-01-31', '2019-02-28', '2019-03-31', '2019-04-30',
               '2019-05-31', '2019-06-30'],
              dtype='datetime64[ns]', freq=None)
'''

print(df.columns)
'''
Index(['c1', 'c2', 'c3', 'c4'], dtype='object')
'''


print(df[['c1', 'c2']])


# 按照index取值
print(df.loc['2019-01-31'])
'''
c1   -0.511065
c2    0.173715
c3    0.460645
c4   -0.105340
Name: 2019-01-31 00:00:00, dtype: float64
'''

# 按照values取值
print(df.iloc[0,1])
'''
-0.515215674883499
'''

df.iloc[0,:] = 0
print(df)

'''
                  c1        c2        c3        c4
2019-01-31  0.000000  0.000000  0.000000  0.000000
2019-02-28 -0.473829  0.647171 -1.026075 -0.630721
2019-03-31  1.112496  2.454119 -0.339265  0.600856
2019-04-30 -0.264615 -0.035386 -0.717795  0.320868
2019-05-31 -0.638794 -0.926775  0.247402 -0.824648
2019-06-30 -0.100243 -1.077409 -1.063229 -1.314213
'''

おすすめ

転載: www.cnblogs.com/setcreed/p/11628303.html