根据数组中的值从索引中选择一系列值

时间:2019-08-07 21:57:25

标签: python pandas numpy

说我有一个类似的系列

mySeries = pd.Series(range(1, 100, 1))
myArray = np.array([[3, 10],[6, 9]])

如何使用myArray中的值作为索引来选择mySeries

我希望结果数组为np.array([[4,11],[7, 10]])

例如,myArray中的(1,1)元素为3,因此我希望所得数组中的(1,1)元素为mySeries中的第3个元素,是4。

3 个答案:

答案 0 :(得分:0)

这是我的解决方案,包括首先将2dim数组展平为1dim,然后恢复原始形状。

import pandas as pd
import numpy as np

mySeries = pd.Series(range(1, 100, 1))
myArray = np.array([[3, 10],[6, 9]])

flatArray = np.asarray(mySeries[myArray.ravel()])
resultArray = flatArray.reshape(myArray.shape)

# Output results
print(resultArray)

哪个输出:

[[ 4 11]
 [ 7 10]]

答案 1 :(得分:0)

resultArray = np.empty(shape=len(myArray), dtype=np.ndarray)
for i in range(len(myArray)):
    row = np.empty(shape=len(myArray[i]))
    for k in range(len(myArray[i])):
        v = mySeries[myArray[i,k]]
        row[k] = v
    resultArray[i] = row

答案 2 :(得分:0)

这是我认为较干净的另一种方法:

>>> newArray = mySeries[myArray.flatten()].values
>>> newArray.shape = myArray.shape
>>> newArray
array([[ 4, 11],
       [ 7, 10]], dtype=int64)