📌  相关文章
📜  NumPy-现有数据数组

📅  最后修改于: 2020-11-08 07:34:30             🧑  作者: Mango


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

numpy.asarray

此函数与numpy.array相似,除了它具有较少的参数外。该例程对于将Python序列转换为ndarray很有用。

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

构造函数采用以下参数。

Sr.No. Parameter & Description
1

a

Input data in any form such as list, list of tuples, tuples, tuple of tuples or tuple of lists

2

dtype

By default, the data type of input data is applied to the resultant ndarray

3

order

C (row major) or F (column major). C is default

以下示例说明如何使用asarray函数。

例子1

# convert list to ndarray 
import numpy as np 

x = [1,2,3] 
a = np.asarray(x) 
print a

其输出如下-

[1  2  3] 

例子2

# dtype is set 
import numpy as np 

x = [1,2,3]
a = np.asarray(x, dtype = float) 
print a

现在,输出将如下所示:

[ 1.  2.  3.] 

例子3

# ndarray from tuple 
import numpy as np 

x = (1,2,3) 
a = np.asarray(x) 
print a

它的输出将是-

[1  2  3]

例子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. Parameter & Description
1

buffer

Any object that exposes buffer interface

2

dtype

Data type of returned ndarray. Defaults to float

3

count

The number of items to read, default -1 means all data

4

offset

The starting position to read from. Default is 0

以下示例演示了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. Parameter & Description
1

iterable

Any iterable object

2

dtype

Data type of resultant array

3

count

The number of items to be read from iterator. Default is -1 which means all data to be read

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

例子1

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

其输出如下-

[0,  1,  2,  3,  4]

例子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.]