[Python] Numpy array 高级用法(4)

前言

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

目录

  • 保存复数complex
  • numpy.dtype 类型

正文

4. 将现有数据转换为 ndarray

使用 numpy.asarray 进行转换 :

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

[Python] Numpy array 高级用法(4)_第1张图片


  • 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

你可能感兴趣的:(Python)