python数据分析——numpy基本用法

发布时间:2024年01月23日

numpy数据类型

在NumPy中,有多种数据类型可用于表示数组的元素。以下是一些常见的NumPy数据类型:

  • int - 整数类型,如int8、int16、int32、int64等。
  • uint -无符号整数类型,如uint8、uint16、uint32、uint64等。
  • float -浮点数类型,如float16、float32、float64等。
  • complex - 复数类型,如complex64、complex128等。 bool - 布尔类型,表示True或False。
  • object -对象类型,可以存储任意Python对象。 string - 字符串类型,如string_。
  • datetime -日期和时间类型,如datetime64。

dtype

检测数据类型

a = np.array([2, 5, 0, 6, 7],dtype=bool)
print(a)
#[ True  True False  True  True]
a = np.array(range(6))
print(a.dtype)

astype

转换类型

b = np.array(range(6))
print("b转换类型后的值为{}".format(b.astype(bool)))
# b转换类型后的值为[False  True  True  True  True  True]

arange

随机数

c=np.arange(1,6,2)
# [1 3 5]

数组的形状

shape

shape是NumPy数组的一个属性,用于返回数组的维度信息。它返回一个元组,其中的每个元素表示数组在对应维度上的大小

例如:(2,3)
shape属性返回了一个元组(2, 3),表示数组的第一维度大小为2,第二维度大小为3。

reshape

reshape是NumPy数组的一个方法,用于改变数组的形状。它接受一个参数,即新的形状,可以是一个元组或整数列表。reshape方法将返回一个具有新形状的新数组,而原始数组保持不变。

如果在reshape方法中指定的新形状中有一个维度为-1,NumPy将根据数组的大小自动计算该维度的大小。

例如,如果原始数组有12个元素,可以将其重塑为(3, -1),-1将被自动计算为4

import numpy as np

a = np.arange(24)
new_a1 = a.reshape((4,6))
new_a2 = a.reshape((2,2,6))

print(a)
#[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
print(new_a1)
# [ [ 0  1  2  3  4  5]
#   [ 6  7  8  9 10 11]
#   [12 13 14 15 16 17]
 #  [18 19 20 21 22 23] ]
print(new_a2)
#[[[ 0  1  2  3  4  5]
# [ 6  7  8  9 10 11]]

# [[12 13 14 15 16 17]
#  [18 19 20 21 22 23]]]

print(a.shape)
#(24,)
print(new_a1.shape)
#(4, 6)
print(new_a2.shape)
#(2, 2, 6)

np.flatten()

是NumPy数组的一个方法,用于将多维数组转换为一维数组。

np.eyes()

np.eye() 是一个 NumPy 函数,用于创建一个二维的单位矩阵(identity matrix)。单位矩阵是一个对角线上的元素都为 1,其余元素都为 0 的方阵。

np.eye(N) 接受一个整数 N 作为参数,并返回一个形状为 (N, N) 的单位矩阵。每个对角线上的元素都是 1,其他位置上的元素都是 0。

以下是 np.eye() 的使用示例:

import numpy as np

# 创建一个形状为 (3, 3) 的单位矩阵
identity_matrix = np.eye(3)
print(identity_matrix)
# 输出
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]

在上面的示例中,np.eye(3) 创建了一个形状为 (3,3) 的单位矩阵。该单位矩阵在主对角线上的元素值均为1,其他位置上的元素值均为0。

你还可以通过指定 k 参数来创建具有偏移主对角线的单位矩阵。例如:

import numpy as np

# 创建一个形状为 (4,4) 偏移主对角线两位的单位矩阵
identity_matrix = np.eye(4, k=2)
print(identity_matrix)
# 输出
# [[0.  0  1  0]
# [0.  0  0  1]
# [0.  0   0   0]
# [0.  0   0   0]]

在上面的示例中,np.eye(4, k=2) 创建了一个形状为 (4,4) 的单位矩阵,其中主对角线向右偏移两位。因此,在第三行和第四行上的主对角线元素值为1。

np.argmax()/np.argmin()

argmax 是 NumPy 中的一个函数,用于返回数组中最大元素的索引值。

语法:numpy.argmax(a, axis=None, out=None)
参数: a:输入的数组。
axis:可选参数,指定沿着哪个轴计算最大值。如果不提供该参数,则返回整个数组中最大元素的索引。默认为 None。
out:可选参数,用于指定输出结果的位置。 返回值:

如果没有指定 axis 参数,则返回整个数组中最大元素的索引。
如果指定了 axis 参数,则根据给定轴计算每行/列/深度维度上最大元素,并返回相应维度上最大元素所在位置的索引。
以下是使用 argmax() 函数获取数组中最大元素索引值的示例:

import numpy as np

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

print(f"Array: {arr}")
print(f"Index of maximum element: {index}")
# 输出
# Array: [1 3 2 5 4]
# Index of maximum element: 3

在上面的示例中,我们有一个一维数组 [1, 3, 2, 5, 4]。通过调用 np.argmax(arr) 函数,我们找到了该数组中最大数字5所在位置(索引为3)。

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
indices = np.argmax(arr, axis=1)

print(f"Array:\n{arr}")
print(f"Indices of maximum elements along each row: {indices}")
# 输出
# Array:
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
# Indices of maximum elements along each row: [2 2 2]

在上面的示例中,我们有一个二维数组 [[1,2,3], [4,5,6], [7,8,9]]。通过调用 np.argmax(arr,axis=1) 函数,我们找到了每一行中最大数字所在位置(索引)。返回结果为一个一维数组 [2,2.2],其中 [2] 表示第一行最大元素(值为3)所在位置的索引,以此类推。

数组和数的计算

算术运算

import numpy as np

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

add_result = arr + 5
sub_result = arr - 5
mul_result = arr * 5
div_result = arr / 5

print(add_result)  # [6 7 8]
print(sub_result)  # [-4 -3 -2]
print(mul_result)  # [5 10 15]
print(div_result)  # [0.2 0.4 0.6]

平方根和指数运算

import numpy as np

arr = np.array([1, 4, 9])

sqrt_result = np.sqrt(arr)
exp_result = np.exp(arr)

print(sqrt_result)  # [1. 2. 3.]
print(exp_result)   # [  2.71828183  54.59815003 810.7788846 ]

数组和数组的计算

算术运算

一维数组

import numpy as np

# 一一对应做运算
arr1 = np.array([1,2,3])
arr2 = np.array([4,5,6])

add_result = arr1 + arr2
sub_result = arr1 - arr2
mul_result = arr1 * arr2
div_result = arr1 / arr2

print(add_result)  # [5 7 9]
print(sub_result)  # [-3 -3 -3]
print(mul_result)  # [4 10 18]
print(div_result)  # [0.25 0.4  0.5]

多维数组

import numpy as np

arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])

add_result = arr1 + arr2
sub_result = arr1 - arr2
mul_result = arr1 * arr2
div_result = arr1 / arr2

print(add_result)
# [[ 6  8]
#  [10 12]]

print(sub_result)
# [[-4 -4]
#  [-4 -4]]

print(mul_result)
# [[ 5 12]
#  [21 32]]

print(div_result)
# [[0.2        0.33333333]
#  [0.42857143 0.5       ]]

统计计算

import numpy as np

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

max_value = np.max(arr, axis=0)  # 沿着轴0计算每列的最大值
min_value = np.min(arr, axis=1)  # 沿着轴1计算每行的最小值
mean_value = np.mean(arr)        # 计算整个数组的平均值
std_value = np.std(arr, axis=None)  # 计算整个数组的标准差

print(max_value)   # [5 6]
print(min_value)   # [1 3 5]
print(mean_value)  # 3.5
print(std_value)   # 1.707825127659933

矩阵运算

  • np.dot()函数执行矩阵乘法
  • .T矩阵转置
import numpy as np

arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])

dot_result = np.dot(arr1, arr2)
transpose_result = arr1.T

print(dot_result)
# [[19 22]
#  [43 50]]

print(transpose_result)
# [[1 3]
#  [2 4]]

在这里插入图片描述

广播规则

当两个数组的形状不同的时候,NumPy会使用广播规则来自动调整数组的形状,以使它们能够参与运算。

广播规则的基本原则是,当两个数组的维度不匹配时,NumPy会尝试通过在缺失的维度上扩展数组来使它们具有相同的形状。广播的过程是自动完成的,无需手动操作。

import numpy as np

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

add_result = arr1 + arr2
mul_result = arr1 * arr2

print(add_result)
# [[2 4 6]
#  [5 7 9]]

print(mul_result)
# [[ 1  4  9]
#  [ 4 10 18]]

import numpy as np

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

add_result = arr1 + arr2
mul_result = arr1 * arr2

print(add_result)
# [[2 3 4]
#  [6 7 8]]

print(mul_result)
# [[ 1  2  3]
#  [ 8 10 12]]

numpy读取数据

在这里插入图片描述
np.loadtxt()函数来读取文本文件中的数据。该函数可以接受文件名作为参数,并返回一个包含文件中数据的NumPy数组

# data = np.loadtxt('data.txt',delimiter=',',skiprows=1)
data = np.loadtxt('data.txt',delimiter=',',dtype='str')
# data = np.loadtxt('data.txt',delimiter=',',skiprows=1,unpack=True)

索引和切片

获取数据

在这里插入图片描述

# 第二行
data[2]
# 第二列
data[:,2]
# 2-4行
data[2:,:]
# 2-4列
data[:,2:]
# 1 3 4行
data[[1,3,4]]
# 1 3 4列
data[:,[1,3,4]]

花式索引:获取不连续的多个点

a是一个二维数组,在花式索引中,第一个列表 [1, 1, 3] 表示要获取的行索引,第二个列表 [2, 3, 0]表示要获取的列索引。
代码的含义是获取数组 a 中的 (1, 2),(1, 3) 和 (3, 0) 这三个位置的元素。

a = np.array([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 5, 2, 1],
    [0, 6, 8, 2]
])
t = a[[1, 1, 3], [2, 3, 0]]
print(t)

在这里插入图片描述

数值修改

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

print(a < 5)
# [[ True  True  True  True]
#  [False False False False]
#  [False False  True  True]
#  [ True False False  True]]

print(a < 5)
a[a < 5] = 0
print(a)
# [[0 0 0 0]
#  [5 6 7 8]
#  [9 5 0 0]
#  [0 6 8 0]]

where

np.where(condition, x, y)
import numpy as np

# 示例1:根据条件选择元素
a = np.array([1, 2, 3, 4, 5])
b = np.where(a > 2, a, 0)
print(b)  # [0 0 3 4 5]

# 示例2:根据条件选择元素,同时处理多维数组
c = np.array([[1, 2, 3],
              [4, 5, 6]])
d = np.where(c > 3, c, -1)
print(d)
# [[-1 -1 -1]
#  [ 4  5  6]]

# 示例3:根据条件选择元素,同时处理多个数组
x = np.array([1, 2, 3, 4, 5])
y = np.array([10, 20, 30, 40, 50])
z = np.where(x > 3, x, y)
print(z)  # [10 20 30  4  5]
  • 在示例1中,我们根据条件 a > 2 选择数组 a 中大于2的元素,对应位置上选择 a 中的元素,否则选择0。
  • 在示例2中,我们根据条件 c > 3 选择数组 c 中大于3的元素,对应位置上选择 c 中的元素,否则选择-1。注意,这里的条件和数组 c
    都是多维的。
  • 在示例3中,我们根据条件 x > 3 选择数组 x 中大于3的元素,对应位置上选择 x 中的元素,否则选择 y 中的元素。

数组的拼接

np.concatenate

np.concatenate:可以在指定的轴上连接两个或多个数组
np.concatenate([a, b])会将数组a和b按照第一个轴(默认为0)进行连接

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

res=np.concatenate([a,b])

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

在这里插入图片描述

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

res=np.concatenate([a,b],axis=1)
[[1 2 5]
 [3 4 6]]

在这里插入图片描述

np.vstack

可以垂直(沿着行方向)堆叠两个或多个数组

import numpy as np

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

result = np.vstack([a, b])
print(result)
# 输出
# [[1 2]
# [3 4]
# [5 6]]

np.hstack

可以水平(沿着列方向)堆叠两个或多个数组。例如,np.hstack([a, b])会将数组a和b按照列方向进行堆叠。

import numpy as np

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

result = np.hstack([a, b])
print(result)
# 输出
# [[1 4]
# [2 5]
# [3 6]]

np.dstack

可以深度堆叠两个或多个三维数组。例如,如果有两个形状为 (M,N) 的二维数组 a 和 b,则 np.dstack([a, b]) 会返回一个形状为 (M,N,2) 的三维数组。

import numpy as np

a = np.array([[1,2],[3,4]])
b = a * -1

result= np.dstack((a,b))
print(result)
# [[[ 1 -1]
  # [ 2 -2]]

 # [[ 3 -3]
  # [ 4 -4]]]

np.column_stack

可以将一维的列向量转换为二维的列,并且能够水平地连接它们在一起。它等效于 hstack 只不过对于 1D 数组工作得更好.

import numpy as npp

x= npp.arange(10)
y= npp.arange(10,20)

result = npp.column_stack((x,y))
print(result)
# 输出
# [[ 0 10]
# [ 1 11]
# [ 2 12]
# [ 3 13]
# [ 4 14]
# [ 5 15]
#[6 16]
#[7 17] 
#[8         
#[9         

np.row_stack

就像 vstack只是它通过追加行来工作而不是列

import numpy as np

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

result = np.row_stack((a,b))
print(result)
# 输出
# [[1 2 3]
#[4 5 6]]

numpy生成随机数

  • np.random.rand():生成一个指定形状的数组,数组中的元素是从[0, 1)区间内均匀分布的随机浮点数
import numpy as np

# 生成一个形状为 (2, 3) 的随机浮点数数组
random_array = np.random.rand(2, 3)
print(random_array)

  • np.random.randint():生成一个指定范围内整型数据类型的随机整数或整型数组
import numpy as np

# 生成一个范围在 [0, 10) 内大小为 (3,) 的一维整型数组
random_int_array = np.random.randint(0, 10, size=(3,))
print(random_int_array)

# 可以通过多个参数控制维度和范围,例如:
random_matrix = np.random.randint(low=1, high=10, size=(2, 4))
print(random_matrix)
  • 对于 size=(3,) 来说:

    • 3 表示数组在第一个维度上有 3 个元素。
    • , 表示这是一个只有一个维度的数组。

    因此,根据给定的 size=(3,) 参数,生成的数组将是一维、包含三个元素(长度为 3)的数组。

  • 对于 size=(3,1) 来说:

    • 第一个数字 3 表示数组在第一个维度上有 3 个元素。
    • 第二个数字 1 表示数组在第二个维度上有 1 个元素。

    因此,根据给定的 size=(3,1) 参数,生成的数组将是一个包含三行、一列的二维数组。

  • np.random.randn():从标准正态分布(平均值为0,标准差为1)中返回一个样本或样本数组
import numpy as np

# 返回一个标准正态分布样本数组
random_array = np.random.randn(3, 4)
print(random_array)
  • np.random.choice():从给定的一维数组中随机选择元素
import numpy as np

# 从 [1, 2, 3, 4, 5] 中随机选择一个数值
random_choice = np.random.choice([1, 2, 3, 4, 5])
print(random_choice) # 1

# 可以指定选择多个元素和是否允许重复选择,例如:
random_choices = np.random.choice([1, 2, 3], size=(2,), replace=True)
print(random_choices) # [1 3]
  • np.random.uniform():从指定范围内均匀分布中返回一个样本或样本数组。
import numpy as np

# 返回一个在 [0, 10) 范围内均匀分布的样本数组
random_uniform = np.random.uniform(0, 10, size=(3,))
print(random_uniform)

# 可以通过多个参数控制维度和范围,例如:
random_uniform_matrix = np.random.uniform(low=1, high=10, size=(2, 4))
print(random_uniform_matrix)
  • np.random.normal():从正态(高斯)分布中返回一个或多个样本值
import numpy as np

# 返回满足标准正态分布(平均值为0,标准差为1)的样本数组
random_normal = np.random.normal(size=(3,))
print(random_normal)

  • np.random.shuffle():随机打乱数组的顺序
import numpy as np

# 随机打乱一维数组的顺序
arr = np.array([1, 2, 3, 4, 5])
np.random.shuffle(arr)
print(arr)[5 2 1 4 3]

# 可以通过多个参数控制维度和范围,例如:
matrix = np.array([[1, 2], [3, 4], [5, 6]])
np.random.shuffle(matrix)
print(matrix)
[[3 4]
 [1 2]
 [5 6]]
  • numpy.random.seed() 函数设置种子
import numpy as np

np.random.seed(123)  # 设置种子为 123

random_value = np.random.rand()
print(random_value)
输出:
0.6964691855978616

在上述示例中,我们使用 np.random.seed(123) 将种子设置为 123。然后,我们调用 np.random.rand() 生成一个随机浮点数,并将结果打印出来。由于我们设置了相同的种子,在每次运行代码时都会得到相同的结果。

通过设置相同的种子值,可以使得每次运行程序时都产生相同的随机序列。这对于需要可重复性和可验证性的实验或模型训练非常有用。

np.copy和np.view

  • copy() 创建一个独立的副本,对副本进行修改不会影响到原始数组。
  • view()创建一个共享内存块的视图,对视图进行修改可能会影响到原始数组
import numpy as np

arr = np.array([1, 2, 3])
arr_copy = arr.copy()

arr_copy[0] = 10

print(arr)       # 输出: [1 2 3]
print(arr_copy)  # 输出: [10 2 3]

import numpy as np

arr = np.array([1, 2, 3])
arr_view = arr.view()

arr_view[0] = 10

print(arr)      # 输出: [10 2 3]
print(arr_view) # 输出: [10 2 3]

inf和nan

在 NumPy 中,inf(无穷大)和 nan(非数值)是特殊的浮点数常量

inf

inf 表示正无穷大,用于表示超过浮点数范围的值。可以通过使用 numpy.inf 来表示。

示例:
import numpy as np

print(np.inf)  # 输出: inf

x = np.array([1, 2, np.inf])
print(x)       # 输出: [ 1.  2. inf]

nan

nan 表示非数值(Not a Number),用于表示不可定义或未定义的结果。可以通过使用 numpy.nan 来表示。

示例:
import numpy as np

print(np.nan)  # 输出: nan

x = np.array([1, 2, np.nan])
print(x)       # 输出: [ 1.  2. nan]

nan 的传播:在进行计算时,如果任何操作涉及到 nan,结果将会是 nan。

示例:

import numpy as np

x = np.array([1, 2, np.nan])
y = np.array([3, 4, 5])

z = x + y
print(z)  # 输出: [nan nan nan]

w = x * y
print(w)  # 输出: [nan nan nan]

比较操作:使用比较运算符(如 <, >, ==)进行比较时,涉及到 nan 的元素会返回布尔值 False。

示例:

import numpy as np

x = np.array([1, 2, np.nan])

print(x < 3)     # 输出: [ True  True False]

计算函数和 nan:许多 NumPy 中的计算函数对于输入包含 nan 的情况都有特殊处理。这些函数通常会忽略或跳过 nan 值,并返回有效的结果。

示例:

import numpy as np

x = np.array([1, 2, np.nan])

print(np.sum(x))       # 输出: nan

print(np.nansum(x))    # 输出: 3.0

检测 nan:可以使用函数如 np.isnan() 来检测数组中的 nan 值。

示例:

import numpy as np

x = np.array([1, 2, np.nan])

print(np.isnan(x))     # 输出: [False False  True]

统计函数

  • np.mean():计算数组的平均值
  • np.median():计算数组的中位数
  • np.sum():计算数组元素的总和
  • np.min():找到数组中的最小值
  • np.max():找到数组中的最大值
  • np.var():计算数组元素的方差
  • np.std():计算数组元素的标准差
import numpy as np

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

mean = np.mean(arr)
print(mean)     # 输出: 3.5

median = np.median(arr)
print(median)   # 输出: 3.5

sum = np.sum(arr)
print(sum)      # 输出: 21

min_val = np.min(arr)
print(min_val)  # 输出: 1

max_val = np.max(arr)
print(max_val)  # 输出: 6

variance = np.var(arr)
print(variance) # 输出: 2.9166666666666665

std_deviation = np.std(arr)
print(std_deviation)   # 输出: 1.707825127659933
文章来源:https://blog.csdn.net/m0_74033027/article/details/135751986
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。