Numpy的一些小操作

下面主要介绍了Numpy中常用的操作及对比,主要包括布尔索引,最值索引以及不同的复制操作。

1. 布尔值当做索引

import numpy as np
# Compares vector to the value 10, # which generates a new Boolean vector [False, True,   False, False].
# It assigns this result to equal_to_ten
vector = numpy.array([5, 10, 15, 20])
equal_to_ten = (vector == 10)
print (equal_to_ten)
print(vector[equal_to_ten])  
[False  True False False]  
[10]
matrix = numpy.array([
                [5, 10, 15], 
                [20, 25, 30],
                [35, 40, 45]
             ])
second_column_25 = (matrix[:,1] == 25)
print (second_column_25)            
print(matrix[second_column_25, :]) 
[False  True False]  
[[20 25 30]]

2. &(与)和|(或)

# We can also perform comparisons with multiple conditions
vector = numpy.array([5, 10, 15, 20])
equal_to_ten_and_five = (vector == 10) & (vector == 5)
print (equal_to_ten_and_five)      
[False False False False]
vector = numpy.array([5, 10, 15, 20])
equal_to_ten_or_five = (vector == 10) | (vector == 5)
vector[equal_to_ten_or_five] = 50
print(vector)           
[50  50 15 20]

3. 不同复制操作对比

  • 直接赋值
#Simple assignments make no copy of array objects or of their data.
a = np.arange(12)
b = a
#a and b are two names for the same ndarray object
print(b is a)
b.shape = 3,4
print (a.shape)
print (id(a))
print (id(b))
True  
(3, 4)  
2440636174864  
2440636174864  
  • 浅复制
# The view method creates a new array object that looks at the same data.
c = a.view()
print(c is a)
c.shape = 2,6
#print a.shape
c[0,4] = 1234
print(a)
False  
[[   0    1    2    3]  
 [1234    5    6    7]   
 [   8    9   10   11]]  
  • 深复制
#The copy method makes a complete copy of the array and its data.
d = a.copy() 
print(d is a)
d[0,0] = 9999
print (d) 
print (a)
False  
[[9999    1    2    3]  
 [1234    5    6    7]  
 [   8    9   10   11]]  
[[   0    1    2    3]  
 [1234    5    6    7]  
 [   8    9   10   11]]

4.最值索引

import numpy as np
data = np.sin(np.arange(20)).reshape(5,4)
print (data)
ind = data.argmax(axis=0)
print( ind)
data_max = data[ind, range(data.shape[1])]
print (data_max)
print(all(data_max == data.max(axis=0)))
[[ 0.          0.84147098  0.90929743  0.14112001]
 [-0.7568025  -0.95892427 -0.2794155   0.6569866 ]
 [ 0.98935825  0.41211849 -0.54402111 -0.99999021]
 [-0.53657292  0.42016704  0.99060736  0.65028784]
 [-0.28790332 -0.96139749 -0.75098725  0.14987721]]
[2 0 3 1]
[0.98935825 0.84147098 0.99060736 0.6569866 ]
True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值