美文网首页
Numpy简单使用

Numpy简单使用

作者: 叶扬风起 | 来源:发表于2019-07-23 08:41 被阅读0次

一、导包

pip install numpy
import numpy as np

二、Numpy中的数组

1. Numpy中的数组

import numpy as np 
my_array = np.array([1, 2, 3, 4, 5]) 
print(type(my_array))    #<class 'numpy.ndarray'>
print(my_array)             #[1 2 3 4 5]
#查看数组维度信息
print(a.shape)               #(5, 5)

2. 创建数组

#1. 指定维度0填充
a = np.zeros((2,2))   # Create an array of all zeros
print(a)              # Prints "[[ 0.  0.]
                      #          [ 0.  0.]]"

#2. 指定维度1填充
b = np.ones((1,2))    # Create an array of all ones
print(b)              # Prints "[[ 1.  1.]]"

#3. 指定维度,指定数填充
c = np.full((2,2), 7)  # Create a constant array
print(c)               # Prints "[[ 7.  7.]
                       #          [ 7.  7.]]"

#4. 这个我怎么说.....
d = np.eye(3)         # Create a 2x2 identity matrix
print(d)              # [[1. 0. 0.]
                      # [0. 1. 0.]
                      # [0. 0. 1.]]
#5. 指定维度随机填充
e = np.random.random((2,2))  # Create an array filled with random values
print(e)                     # Might print "[[ 0.91940167  0.08143941]
                             #               [ 0.68744134  0.87236687]]"

3. 数组类型

  • 类型:布尔(bool)、整数(int)、无符号整数(uint)、浮点数(float)和复数
  • 类型转换
import numpy as np
x = np.float32(1.0)
y = np.int_([1,2,4])
z = np.arange(3, dtype=np.uint8)
print(x)        #1.0
print(y)        #[1 2 4]
print(z)        #[0 1 2]
#指定dtype
np.array([1, 2, 3], dtype='f')     #array([ 1.,  2.,  3.], dtype=float32)
#使用.astype()方法(首选)或类型本身作为函数
z.astype(float)                    #array([  0.,  1.,  2.])
np.int8(z)                         #array([0, 1, 2], dtype=int8)
  • 查看类型
z.dtype                      #dtype('uint8')
#是否为整数
d = np.dtype(int)            #dtype('int32')
np.issubdtype(d, int)        #True
np.issubdtype(d, float)      #False

4. 切片

切片(Slicing): 与Python列表类似,可以对numpy数组进行切片。由于数组可能是多维的,因此必须为数组的每个维指定一个切片

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
#需要指定每个维度,然后指定一个切片
b = a[:2, 1:3]
print(b)         #[[2 3]
                 # [6 7]]
#引用类型,修改指针值后,其余指向该值指针值发生变化
print(a[0, 1])   # Prints "2"
b[0, 0] = 77     # b[0, 0] is the same piece of data as a[0, 1]
print(a[0, 1])   # Prints "77"
  • 整数索引与切片索引混合使用
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

row_r1 = a[1, :]    # Rank 1 view of the second row of a
row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
print(row_r1, row_r1.shape)  # Prints "[5 6 7 8] (4,)"
print(row_r2, row_r2.shape)  # Prints "[[5 6 7 8]] (1, 4)"

col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape)  # Prints "[ 2  6 10] (3,)"
print(col_r2, col_r2.shape)  # Prints "[[ 2]
                             #          [ 6]
                             #          [10]] (3, 1)"

整数数组索引: 使用切片索引到numpy数组时,生成的数组视图将始终是原始数组的子数组。 相反,整数数组索引允许你使用另一个数组中的数据构造任意数组。

import numpy as np

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

print(a[[0, 1, 2], [0, 1, 0]])                # Prints "[1 4 5]"

print(np.array([a[0, 0], a[1, 1], a[2, 0]]))  # Prints "[1 4 5]"

print(a[[0, 0], [1, 1]])                      # Prints "[2 2]"

print(np.array([a[0, 1], a[0, 1]]))           # Prints "[2 2]"
  • 整数数组索引的一个有用技巧是从矩阵的每一行中选择或改变一个元素
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])

print(a)  # prints "array([[ 1,  2,  3],
          #                [ 4,  5,  6],
          #                [ 7,  8,  9],
          #                [10, 11, 12]])"

b = np.array([0, 2, 0, 1])

print(a[np.arange(4), b])  # Prints "[ 1  6  7 11]"

a[np.arange(4), b] += 10

print(a)  # prints "array([[11,  2,  3],
          #                [ 4,  5, 16],
          #                [17,  8,  9],
          #                [10, 21, 12]])
  • 布尔数组索引: 布尔数组索引允许你选择数组的任意元素。通常,这种类型的索引用于选择满足某些条件的数组元素。
import numpy as np

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

bool_idx = (a > 2)   # Find the elements of a that are bigger than 2;
                     # this returns a numpy array of Booleans of the same
                     # shape as a, where each slot of bool_idx tells
                     # whether that element of a is > 2.

print(bool_idx)      # Prints "[[False False]
                     #          [ True  True]
                     #          [ True  True]]"

# of bool_idx
print(a[bool_idx])  # Prints "[3 4 5 6]"

print(a[a > 2])     # Prints "[3 4 5 6]"

5. 索引方法

  • Ellipsis 扩展为:x.ndim生成与长度相同的选择元组所需的对象数。可能只存在一个省略号。
x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
x[...,0]    #array([[1, 2, 3],
            #    [4, 5, 6]])
  • newaxis对象用于将结果选择的维度扩展一个单位长度维度。 添加的维度是选择元组中newaxis对象的位置。
x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
x[:,np.newaxis,:,:].shape    #(2, 1, 3, 1)

注意: numpy.newaxis可以在所有切片操作中使用newaxis对象来创建长度为1的轴。 newaxis是'None'的别名,'None'可以代替它使用相同的结果

三、数组中的数学

  1. 普通运算
import numpy as np

x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

#加
print(x + y)
print(np.add(x, y))
# [[ 6.0  8.0]
#  [10.0 12.0]]

#减
print(x - y)
print(np.subtract(x, y))
# [[-4.0 -4.0]
#  [-4.0 -4.0]]

#乘
print(x * y)
print(np.multiply(x, y))
# [[ 5.0 12.0]
#  [21.0 32.0]]

#除
print(x / y)
print(np.divide(x, y))
# [[ 0.2         0.33333333]
#  [ 0.42857143  0.5       ]]

相关文章

网友评论

      本文标题:Numpy简单使用

      本文链接:https://www.haomeiwen.com/subject/ilkglctx.html