我尝试通过索引从np.array
或pd.dataframe
获取值。 假设原始值形状是[x,y]
,我的索引是一个形状是[x,z]
的数组。 我想按索引取每一列的值。 这意味着每个列将更改为z
列。 我试图直接使用take
,但这不是我想要的。 因此,我必须应用for columns循环方法。 我的代码如下:
import numpy as np
arr = np.asarray([[0, 1, 2], [1, 2, 3], [2, 3, 4]])
print(f"input array:\n{arr}")
indices = np.asarray([[-1, 0, 1], [-1, -1, 0]]).T
print(f"indices:\n{indices.shape}")
res_0 = arr.take(indices)
print(f"take directly:\n{res_0}")
result_list = []
for i in range(arr.shape[1]):
result_list.append(arr[:, i].take(indices))
res_1 = np.concatenate(result_list, axis=-1)
print(f"expected result:\n{res_1}")
有没有更高效的方式来实现这一点?
您可以尝试将np.apply_along_axis
与np.concatenate
一起使用
arr = np.asarray([[0, 1, 2], [1, 2, 3], [2, 3, 4]])
indices = np.asarray([[-1, 0, 1], [-1, -1, 0]]).T
res_1 = np.concatenate(np.apply_along_axis(lambda x: x[indices],1, arr),1)
res_1
# array([[2, 2, 3, 3, 4, 4],
# [0, 2, 1, 3, 2, 4],
# [1, 0, 2, 1, 3, 2]])