目录

NumPy - 来自现有数据的数组( Array from Existing Data)

在本章中,我们将讨论如何从现有数据创建数组。

numpy.asarray

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

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

构造函数采用以下参数。

Sr.No. 参数和描述
1

a

以任何形式输入数据,例如列表,元组列表,元组,元组元组或列表元组

2

dtype

默认情况下,输入数据的数据类型将应用于生成的ndarray

3

order

C(行专业)或F(专业专业)。 C是默认的

以下示例显示了如何使用asarray函数。

例子1 (Example 1)

# convert list to ndarray 
import numpy as np 
x = [1,2,3] 
a = np.asarray(x) 
print a

其产出如下 -

[1  2  3] 

例子2 (Example 2)

# dtype is set 
import numpy as np 
x = [1,2,3]
a = np.asarray(x, dtype = float) 
print a

现在,输出如下 -

[ 1.  2.  3.] 

例子3 (Example 3)

# ndarray from tuple 
import numpy as np 
x = (1,2,3) 
a = np.asarray(x) 
print a

它的输出是 -

[1  2  3]

例子4 (Example 4)

# ndarray from list of tuples 
import numpy as np 
x = [(1,2,3),(4,5)] 
a = np.asarray(x) 
print a

这里的输出如下 -

[(1, 2, 3) (4, 5)]

numpy.frombuffer

此函数将缓冲区解释为一维数组。 暴露缓冲区接口的任何对象都用作返回ndarray参数。

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

构造函数采用以下参数。

Sr.No. 参数和描述
1

buffer

任何暴露缓冲区接口的对象

2

dtype

返回的ndarray的数据类型。 默认为浮动

3

count

要读取的项目数,默认值-1表示所有数据

4

offset

从中读取的起始位置。 默认值为0

例子 (Example)

以下示例演示了frombuffer函数的frombuffer

import numpy as np 
s = 'Hello World' 
a = np.frombuffer(s, dtype = 'S1') 
print a

这是它的输出 -

['H'  'e'  'l'  'l'  'o'  ' '  'W'  'o'  'r'  'l'  'd']

numpy.fromiter

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

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

这里,构造函数采用以下参数。

Sr.No. 参数和描述
1

iterable

任何可迭代的对象

2

dtype

结果数组的数据类型

3

count

从迭代器中读取的项数。 默认值为-1表示要读取的所有数据

以下示例显示如何使用内置range()函数返回列表对象。 此列表的迭代器用于形成ndarray对象。

例子1 (Example 1)

# create list object using range function 
import numpy as np 
list = range(5) 
print list

其输出如下 -

[0,  1,  2,  3,  4]

例子2 (Example 2)

# obtain iterator object from list 
import numpy as np 
list = range(5) 
it = iter(list)  
# use iterator to create ndarray 
x = np.fromiter(it, dtype = float) 
print x

现在,输出如下 -

[0.   1.   2.   3.   4.]
↑回到顶部↑
WIKI教程 @2018