首页 > Python3教程 > Python扩展程序库 -- NumPy

NumPy 从已有数组创建新数组

将Python array_like对象转换为Numpy数组

通常,在Python中排列成array-like结构的数值数据可以通过使用array()函数转换为数组。最明显的例子是列表和元组。

一些对象可能支持数组协议并允许以这种方式转换为数组。找出对象是否可以使用array()转换为一个数组numpy 数组的简单方法很简单,只要试一下(Python方式)。

import numpy as np

x = np.array((2,3,1,0))
print(x) # [2 3 1 0]

x = np.array([2, 3, 1, 0])
print(x) # [2 3 1 0]

x = np.array([[1,2.0],[0,0],(1+1j,3.)]) # note mix of tuple and lists,and types
print(x)
# [[1.+0.j 2.+0.j]
# [0.+0.j 0.+0.j]
# [1.+1.j 3.+0.j]]

x = np.array([[ 1.+0.j, 2.+0.j], [ 0.+0.j, 0.+0.j], [ 1.+1.j, 3.+0.j]])
print(x)
# [[1.+0.j 2.+0.j]
# [0.+0.j 0.+0.j]
# [1.+1.j 3.+0.j]]

numpy.asarray

函数类似于numpy.array,除了它有较少的参数。 这个函数对于将 Python 序列转换为ndarray非常有用。

numpy.asarray(a, dtype = None, order = None) 

函数接受下列参数:

序号 参数及描述
1. a 任意形式的输入参数,比如列表、列表的元组、元组、元组的元组、元组的列表
2. dtype 通常,输入数据的类型会应用到返回的ndarray
3. order 'C'为按行的 C 风格数组,'F'为按列的 Fortran 风格数组
import numpy as np

# 列表转换为 ndarray
x = [1, 2, 3]
a = np.asarray(x)
print(a) # [1 2 3]

# 元组转换为 ndarray
x = (1,2,3)
a = np.asarray(x)
print (a) # [1 2 3]

# 元组列表转换为 ndarray
x = [(1,2,3),(4,5)]
a = np.asarray(x)
print (a) # [(1, 2, 3) (4, 5)]

# 设置 dtype 参数
x = [1,2,3]
a = np.asarray(x, dtype = float)
print (a) # [1. 2. 3.]

numpy.frombuffer

numpy.frombuffer 用于实现动态数组。

numpy.frombuffer 接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。

注:buffer 是字符串的时候,Python3 默认 str 是 Unicode 类型,所以要转成 bytestring 在原 str 前加上 b。

numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0) 

函数接受下列参数:

序号 参数及描述
1. buffer 任何暴露缓冲区借口的对象
2. dtype 返回数组的数据类型,默认为float
3. count 需要读取的数据数量,默认为-1,读取所有数据
4. offset 需要读取的起始位置,默认为0
import numpy as np

s = b'Hello World'
a = np.frombuffer(s, dtype='S1')
print(a) # [b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']

numpy.fromiter

此函数从任何可迭代对象构建一个ndarray对象,返回一个新的一维数组。

numpy.fromiter(iterable, dtype, count = -1) 

函数接受下列参数:

序号 参数及描述
1. iterable 任何可迭代对象
2. dtype 返回数组的数据类型
3. count 需要读取的数据数量,默认为-1,读取所有数据
import numpy as np

# 使用 range 函数创建列表对象
list = range(6)
it = iter(list)

# 使用迭代器创建 ndarray
x = np.fromiter(it, dtype=float)
print(x) # [0. 1. 2. 3. 4. 5.]
关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。