python编程入门----numpy不常见的小细节

import numpy as nppython

#### 生成ndarray数组对象(zeros,ones,eye)数组

  1. np.zeros(5) == np.zeros((5,)) #意思都是建立numpy的一维数组,该例的答案是[0,0,0,0,0],(5,)表示第一个参数
  2. a=random.randn(2,3) # 建立 randn(size) 服从 X~N(0,1) 的正态分布随机数组
  3. b=random.randint([low,high],size) #建立在[low, high]间的数组;a=random.randint(100,200,(3,3))

#### 将其余对象转化为ndarray数组数据结构

  1. numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0) #接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。
  2. numpy.asarray((1,2,3)) #将元组变为ndarray
  3. numpy.fromiter(iterable, dtype, count=-1) #从可迭代对象中创建 ndarray 对象,返回一维数组
  • 例:
import numpy as np 
# 使用 range 函数建立列表对象
list=range(5)
it=iter(list)     
# 使用迭代器建立 ndarray
x=np.fromiter(it, dtype=float)
print(x)

#### numpy从数值范围生成数组dom

  1. numpy.arange(start, end, step, dtype)
  2. numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) #建立一个一维数组,数组是一个等差数列构成的
  3. np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None) #函数用于建立一个于等比数列

#### Numpy--结构化数据类型函数

  • numpy中支持不少数据类型,好比int,float等,也能够本身使用dtype()本身新定义一个数据类型,这个数据类型可能相似于C中的数据结构。
student = np.dtype([('name','S20'),  ('age',  'i1'),  ('marks',  'f4')]) 
那么至关于c中:
struct student{
    char name[20];
    int age;// 8位整型数
    float marks // 32位浮点数
import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) 
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student) 
print(a) # 数组的 dtype 为 int8(一个字节
x = np.array([1,2,3,4,5], dtype = np.int8)  
print (x.itemsize)

#### numpy高级索引 数组能够由整数数组索引、布尔索引及花式索引oop

  1. 整数数组索引
q = np.array([[1,2], [3,4], [5,6]])
y = q[[0,1,2],  [0,1,0]]
print y
#[1, 4, 5]

2.布尔索引spa

import numpy as np
x = np.array([[  0,  1,  2],[  3,  4,  5],[  6,  7,  8],[  9,  10,  11]])  
print  ('大于 5 的元素是:')
print (x[x >  5])
#[ 6  7  8  9 10 11]
#过滤数组中的非复数元素
a = np.array([1,  2+6j,  5,  3.5+5j])  
print (a[np.iscomplex(a)])
#[2.0+6.j  3.5+5.j]

3.花式索引code

import numpy as np
x=np.arange(32).reshape((8,4))
print (x[np.ix_([1,5,7,2],[0,3,1,2])])
'''
传入多个索引数组(要使用np.ix_)
[[ 4  7  5  6]
 [20 23 21 22]
 [28 31 29 30]
 [ 8 11  9 10]]
'''

- numpy迭代器****

  1. **np.nditer(order, op_flags, flags) ** #默认行遍历优先,order遍历顺序,op_flags控制列表是否可读写,flags外部循环
#1
a = np.arange(6).reshape(2,3)
for x in np.nditer(a.T):
    print (x, end=", " )

for x in np.nditer(a.T.copy(order='C')):
    print (x, end=", " )
#输出(俩个):0, 1, 2, 3, 4, 5, 
#可见a的存储与a.T同样在内存中
#2
a = np.arange(0,60,5) 
a = a.reshape(3,4)  
for x in np.nditer(a, op_flags=['readwrite']): 
    x[...]=2*x 
print ('修改后的数组是:')
修改后的数组是:
[[  0  10  20  30]
 [ 40  50  60  70]
 [ 80  90 100 110]]
 #3
a = np.arange(0,60,5)
a = a.reshape(3,4)
print ('原始数组是:')
print ('修改后的数组是:')
for x in np.nditer(a, flags =  ['external_loop'], order =  'F'):
   print (x, end=", " )
   
原始数组是:
[[ 0  5 10 15]
 [20 25 30 35]
 [40 45 50 55]]
 修改后的数组是:
[ 0 20 40], [ 5 25 45], [10 30 50], [15 35 55],
相关文章
相关标签/搜索