如何获取NumPy数组在特定索引位置的值
有时我们需要从源Numpy数组中移除数值,并在目标数组的特定索引处添加它们。在NumPy中,我们有这样的灵活性,我们可以从一个数组中移除数值并将其添加到另一个数组中。我们可以使用numpy.put()函数来执行这个操作,它可以应用于所有形式的数组,如一维、二维等。
示例 1:
# Importing Numpy module
import numpy as np
# Creating 1-D Numpy array
a1 = np.array([11, 10, 22, 30, 33])
print("Array 1 :")
print(a1)
a2 = np.array([1, 15, 60])
print("Array 2 :")
print(a2)
print("\nTake 1 and 15 from Array 2 and put them in\
1st and 5th position of Array 1")
a1.put([0, 4], a2)
print("Resultant Array :")
print(a1)
输出:
在上面的例子中,我们采取两个一维数组,并在特定的位置将数值从一个数组转移到另一个数组。
示例 2:
# Importing Numpy module
import numpy as np
# Creating 2-D Numpy array
a1 = np.array([[11, 10, 22, 30],
[14, 58, 88, 100]])
print("Array 1 :")
print(a1)
a2 = np.array([1, 15, 6, 40])
print("Array 2 :")
print(a2)
print("\nTake 1, 15 and 6 from Array 2 and put them in 1st,\
4th and 7th positions of Array 1")
a1.put([0, 3, 6], a2)
print("Resultant Array :")
print(a1)
输出:
在上面的例子中,我们采取两个不同的数组,并在特定的位置将数值从一维数组转移到二维数组。
示例 3:
# Importing Numpy module
import numpy as np
# Creating 3-D Numpy array
a1 = np.array([[[11, 25, 7], [30, 45, 55], [20, 45, 7]],
[[50, 65, 8], [70, 85, 10], [11, 22, 33]],
[[19, 69, 36], [1, 5, 24], [4, 20, 9]]])
print("Array 1 :")
print(a1)
# Creating 2-D array
a2 = np.array([[1, 15, 10],
[6, 40, 50],
[11, 5, 10]])
print("\nArray 2 :")
print(a2)
print("\nTake 1, 15, 10, 6, 40 and 50 from Array 2 and put\
them in 1st, 3rd, 5th, 9th, 11th and 15th positions of Array 1")
a1.put([0, 2, 4, 8, 10, 14], a2)
print("Resultant Array :")
print(a1)
输出:
在上面的例子中,我们采取两个不同的数组,并在特定的位置将数值从二维数组转移到三维数组。一个问题出现了,如果出现界外索引,会发生什么?为此,我们在numpy.put()函数中有三种模式
mode = {‘raise’, ‘wrap’, ‘clip’}
- ‘raise’ – 提出一个错误(默认)。
- ‘wrap’ – 绕行
- ‘clip’ – 夹到范围内
例子4:mode=’raise’
# Importing Numpy module
import numpy as np
# Creating 2-D Numpy array
a1 = np.array([[11, 10, 22],
[14, 58, 88]])
print("Array 1 :")
print(a1)
a2 = np.array([[1, 15, 6],
[40, 50, 70]])
print("Array 2 :")
print(a2)
print("\nTake 1 and 15 from Array 2 and put them in 1st \
and 5th positions of Array 1")
print("by mistake we write the index which is out of bound,\
now mode will play its role")
a1.put([0, 15], a2, mode='raise')
print("\nResultant Array :")
print(a1)
输出:
在上面的例子中,mode=’raise’会在指数超出边界时产生错误。
例子5:mode=’clip’
# Importing Numpy module
import numpy as np
# Creating 2-D Numpy array
a1 = np.array([[11, 10, 22],
[14, 58, 88]])
print("Array 1 :")
print(a1)
a2 = np.array([[1, 15, 6],
[40, 50, 70]])
print("Array 2 :")
print(a2)
print("\nTake 1 and 15 from Array 2 and put them in 1st and\
5th positions of Array 1")
print("by mistake we write the index which is out of bound,\
now mode will play its role")
a1.put([0, 15], a2, mode = 'clip')
print("\nResultant Array :")
print(a1)
输出:
在上面的例子中,mode=’clip’替换了沿轴的最后一个元素,而没有引发任何错误。