Python Numpy recarray.put()函数
在numpy中,数组可以有一个包含字段的数据类型,类似于电子表格中的列。一个例子是[(a, int), (b, float)] ,其中数组中的每个条目是一对(int, float)。通常情况下,这些属性使用字典查询,如arr[‘a’] 和 arr[‘b’] 。记录数组允许字段作为数组的成员被访问,使用arr.a和arr.b。
numpy.recarray.put()函数用给定的值替换一个记录数组中的特定元素。索引工作在扁平化的目标数组上。
语法: numpy.recarray.put(indices, values, mode='raise')
参数:
indices : [array_like] 目标索引,被解释为整数。
values : [array_like] 在目标索引中放置数值。如果values比ind短,它将在必要时被重复。
mode : [‘raise’, ‘wrap’, ‘clip’, optional] 指定界外指数的行为方式。
返回: [ndarray] 结果数组。
代码#1:
# Python program explaining
# numpy.recarray.put() method
# importing numpy as geek
import numpy as geek
# creating input array with 2 different field
in_arr = geek.array([(1.0, 2), (3.0, -4), (5.0, 6),
(7.0, 8), (9.0, -4), (11.0, -2)],
dtype =[('a', float), ('b', int)])
print ("Input array : ", in_arr)
# convert it to a record array,
# using arr.view(np.recarray)
rec_arr = in_arr.view(geek.recarray)
print("Record array of float: ", rec_arr.a)
print("Record array of int: ", rec_arr.b)
# applying recarray.put methods
# to float record array in default mode
rec_arr.a.put( [0, 2], [-14, 15])
print ("Output float array in default mode : ", rec_arr.a)
# applying recarray.put methods
# to float record array in clip mode
rec_arr.a.put( 13, -4, mode ='clip')
print ("Output float array in clip mode : ", rec_arr.a)
# applying recarray.put methods
# to int record array
rec_arr.b.put([1, 2, 4], [10, 15, 20])
print ("Output int array in default mode : ", rec_arr.b)
# applying recarray.put methods
# to int record array in clip mode
rec_arr.b.put(8, 100, mode ='clip')
print ("Output int array in clip mode : ", rec_arr.b)
输出:
Input array : [( 1., 2) ( 3., -4) ( 5., 6) ( 7., 8) ( 9., -4) (11., -2)]
Record array of float: [ 1. 3. 5. 7. 9. 11.]
Record array of int: [ 2 -4 6 8 -4 -2]
Output float array in default mode : [-14. 3. 15. 7. 9. 11.]
Output float array in clip mode : [-14. 3. 15. 7. 9. -4.]
Output int array in default mode : [ 2 10 15 8 20 -2]
Output int array in clip mode : [ 2 10 15 8 20 100]