numpy的操作
import numpy as np
vector = np.array([5, 10, 15, 20])
vector
array([ 5, 10, 15, 20])
类型及转换
数据格式汇总及type, astype, dtype区别
https://blog.youkuaiyun.com/sinat_36458870/article/details/78946053
查看数据类型 df.dtype
vector.dtype
dtype('int32')
转换数据类型 df.astype(‘int’)
数据列作为整数,astype
vector.astype('float')
array([ 5., 10., 15., 20.])
# 所有元素求和
vector.sum()
50
matrix = np.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
matrix.sum(axis=1)
array([ 30, 75, 120])
dy.type和 dy.astype的区别
a.dtype = 'float32’当64–32 的时候shape会翻倍[维度翻倍]
numpy读取数据作为numpy的数组,默认的dtype是float64,因此使用astype函数
来源:
https://blog.youkuaiyun.com/sinat_36458870/article/details/78946053
数据变换
向下取整 int()
int(3.14)
3
向上取整 math.ceil()
import math
math.ceil(3.14)
4
求指数 np.exp()
np.exp(matrix)
array([[1.48413159e+02, 2.20264658e+04, 3.26901737e+06],
[4.85165195e+08, 7.20048993e+10, 1.06864746e+13],
[1.58601345e+15, 2.35385267e+17, 3.49342711e+19]])
开方 np.sqrt()
np.sqrt(matrix)
array([[2.23606798, 3.16227766, 3.87298335],
[4.47213595, 5. , 5.47722558],
[5.91607978, 6.32455532, 6.70820393]])
多维变一维 matrix.ravel()
# 多维变一维
matrix.ravel()
array([ 5, 10, 15, 20, 25, 30, 35, 40, 45])
矩阵的扩展 np.tile(df,(a,b))
行的a倍,列变成b倍
a = np.arange(0, 40, 10)
b = np.tile(a, (3, 5)) # 行变成3倍,列变成5倍
a
array([ 0, 10, 20, 30])
b
array([[ 0, 10, 20, 30, 0, 10, 20, 30, 0, 10, 20, 30, 0, 10, 20, 30,
0, 10, 20, 30],
[ 0, 10, 20, 30, 0, 10, 20, 30, 0, 10, 20, 30, 0, 10, 20, 30,
0, 10, 20, 30],
[ 0, 10, 20, 30, 0, 10, 20, 30, 0, 10, 20, 30, 0, 10, 20, 30,
0, 10, 20, 30]])
矩阵的拼接
# 矩阵的拼接:
a = np.floor(10*np.random.random((2,2)))
b = np.floor(10*np.random.random((2,2)))
a
array([[0., 6.],
[5., 9.]])
b
array([[3., 6.],
[8., 7.]])
水平拼接 np.hstack((a,b))
horizontal–水平拼接
np.hstack((a,b))
array([[0., 6., 3., 6.],
[5., 9., 8., 7.]])
竖直拼接 np.vstack((a,b))
Vertical–竖值拼接
# 竖直拼接
np.vstack((a,b))
array([[0., 6.],
[5., 9.],
[3., 6.],
[8., 7.]])
a = np.floor(10*np.random.random((2,12)))
a
array([[1., 4., 3., 2., 5., 5., 7., 7., 1., 8., 3., 3.],
[4., 3., 9., 8., 2., 2., 6., 2., 7., 3., 9., 7.]])
竖直分割 np.hsplit(a,3)
函数的作用是将数组a横向等分成三个数组
# 竖直分割
np.hsplit(a,3)
[array([[1., 4., 3., 2.],
[4., 3., 9., 8.]]),
array([[5., 5., 7., 7.],
[2., 2., 6., 2.]]),
array([[1., 8., 3., 3.],
[7., 3., 9., 7.]])]
a = np.floor(10*np.random.random((12,2)))
水平分割 np.vsplit(a,3)
函数的作用是将数组a竖向等分成三个数组
# 水平分割
np.vsplit(a,3)
[array([[9., 8.],
[8., 9.],
[1., 1.],
[6., 6.]]),
array([[2., 3.],
[2., 7.],
[4., 3.],
[4., 8.]]),
array([[6., 8.],
[1., 7.],
[9., 2.],
[3., 2.]])]