使用现有数据创建 Numpy 数组

原文:https://www.studytonight.com/numpy/python-numpy-array-creation-using-existing-data

在本教程中,我们将介绍如何使用 Numpy 库中的现有数据创建数组。

Numpy 库提供了从现有数据创建数组的各种方法,如下所示:

  1. numpy.asarray

  2. numpy.frombuffer

  3. numpy.fromiter

现在,我们将在接下来的章节中逐一介绍上述内容。

1.Python 序列到数组-使用numpy.asarray

例程numpy.asarray用于将 Python 序列转换为数组。numpy.asarraynumpy.array有些相似,但参数比numpy.array少。该功能主要用于利用现有数据创建数组,其形式为列表,或元组

下面给出了用于numpy.asarray的所需语法:

numpy.asarray(sequence,  dtype, order)

参数:

让我们讨论上述构造器的参数:

  1. 序列: 该参数用于指示要转换为蟒阵的蟒序列。

  2. 数据类型: 此参数用于指示数组中每一项的数据类型。

  3. 顺序: 该参数可设置为 C 或 f,默认为 C

让我们举几个例子来看看这种数组创建技术的工作原理。

示例 1 -使用元组的数组

在下面给出的示例中,我们将使用元组创建一个数组:

import numpy as np  

# Python tuple
l = (34,7,8,78)
# creating array using the tuple
a = np.asarray(l)

print(type(a))  
print(a)

<类‘num py . ndaarray’> 【34 7 8 78】

示例 2 -使用列表的数组

现在我们将使用多个列表创建一个数组。其代码如下:

import numpy as np  

# Python list
l = [[1,2,3],[8,9],[5,7]] 
# creating array from list 
b = np.asarray(l)

print(type(b))  
print(b)

<类> 【list([1,2,3]) list([8,9]) list([5,7])

2.使用numpy.frombuffer

numpy.frombuffer例程用于通过使用指定的缓冲区来创建数组。

下面给出了用于numpy.frombuffer的所需语法:

numpy.frombuffer(buffer, dtype, count, offset)

参数:

让我们讨论上述构造器的参数:

  • 缓冲区: 该参数用于表示一个暴露缓冲区接口的对象。

  • dtype: 此参数用于表示返回的数据类型数组的数据类型。此参数的默认值为 0。

  • 计数: 此参数表示返回数组的长度。此参数的默认值为-1。

  • 偏移量: 该参数表示读取的起始位置。此参数的默认值为 0。

现在让我们讨论一些使用 frombuffer 例程的例子。

基本示例:

下面是我们将使用numpy.frombuffer例程的代码片段:

import numpy as np  

# intialize bytes
l = b'StudyTonight!'  
print(type(l))  

a = np.frombuffer(l, dtype = "S1")  
print(a)  
print(type(a))

<类字节】> 【b ' s ' b ' t ' u ' b ' y ' b ' t ' o ' b ' n ' b ' b ' h ' b ' t '!"] <类‘num py . ndaarray’>

3.使用numpy.fromiter

例程numpy.fromiter用于通过使用可迭代对象来创建数组。这个例程主要返回一个一维数组对象。

下面给出了用于numpy.fromiter的所需语法:

numpy.fromiter(iterable, dtype, count)

参数:

让我们讨论上述构造器的参数:

  1. 可迭代: 该参数主要用于表示可迭代对象。

  2. 数据类型: 该参数用于表示结果数组项的数据类型。

  3. 计数: 此参数用于表示从数组中的缓冲区读取的项目数。

让我们举一个使用这个例程的例子。

基本示例:

下面是我们将使用numpy.fromiter的代码片段:

import numpy as np  

# using python tuple
tup = (2,4,6,20)  
# create an iterator
it = iter(tup)  

# create ndarray using the iterator
x = np.fromiter(it, dtype = float)  

print(x)  
print(type(x))

【2。4.6.20.] <类‘num py . ndaarray’>

摘要

本教程是关于如何使用现有数据在 numpy 中创建数组的,我们已经介绍了使用它们的语法和示例来实现这一点的不同方法。