提问者:小点点

有没有任何有效的方法从numpy数组或pandas数据帧中按索引沿行取值?


我尝试通过索引从np.arraypd.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}")

有没有更高效的方式来实现这一点?


共1个答案

匿名用户

您可以尝试将np.apply_along_axisnp.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]])