【问题标题】:Select values in series based on indices from values in array根据数组中值的索引选择系列值
【发布时间】:2019-08-07 21:57:25
【问题描述】:

假设我有一个类似的系列

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 中的第三个元素,即 4。

【问题讨论】:

  • 这很复杂。您的 np,array 是一个二维数组,而 Series 设计为一维“数组”。但是,在某些条件下,使用 DataFrame 是可能的。

标签: python pandas numpy


【解决方案1】:

这是我的解决方案,包括首先将 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]]

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:

      这是一种我认为更简洁的替代方法:

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

      【讨论】:

        猜你喜欢
        • 2018-02-08
        • 2017-05-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-13
        • 2019-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-02
        相关资源
        最近更新 更多