目录

  • 前言
  • 正文
  • 将现有数据转换为 ndarray
  • list转ndarray
  • 改变默认类型
  • tuple 转 ndarray
  • list of tuples 转 ndarray
  • numpy.frombuffer
  • 迭代器 iterator 转 ndarray


前言

最近在看 [Numpy文档][1] 和 [tutorialspoint Numpy Tutorial][2] 时,发现了一下之前没用过的ndarray高级用法,加上我之前知道的方法,总结一下。以后会陆续更新。

正文

将现有数据转换为 ndarray

使用 numpy.asarray 进行转换 :

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

python numpy.asarray python numpy.asarray转高度图_numpy

list转ndarray

''' list '''
import numpy as np 

x = [1,2,3] 
a = np.asarray(x) 
print(a)
# 输出:
[1  2  3]

改变默认类型

import numpy as np 

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

tuple 转 ndarray

x = (1,2,3) 
a = np.asarray(x) 
print(a)
# 输出:
[1  2  3]

list of tuples 转 ndarray

import numpy as np 

x = [(1,2,3),(4,5)] 
a = np.asarray(x) 
print(a)
# 输出:
[(1, 2, 3) (4, 5)]

numpy.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']

迭代器 iterator 转 ndarray

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

参考网页 : https://www.tutorialspoint.com/numpy/numpy_array_from_existing_data.htm
[1]: https://docs.scipy.org/doc/
[2]: https://www.tutorialspoint.com/numpy/index.htm