【问题标题】:Use index of one array to extract value from list to be appended into new array (Python)使用一个数组的索引从列表中提取值以附加到新数组中(Python)
【发布时间】:2021-03-28 03:03:31
【问题描述】:

如果我有一个包含一组索引的numpy 数组,我将如何将这些索引应用到数据列表中,从而提取相应的数据值并将它们附加到新的numpy 数组中?

我尝试使用的代码是这样的:

second_index = np.zeros(len(first_index))

for i in range(len(first_index)):
    second_index[i] = data[first_index[i]]
print(second_index)

first_indexsecond_index 都是一维 numpy 数组,我希望在 first_indexsecond_index 中看到相同数量的元素。但是,我收到以下错误消息

TypeError: list indices must be integers or slices, not numpy.float64

我应该改用嵌套的for-loops 并在两个不同的范围内执行循环吗?

感谢您的任何建议!

【问题讨论】:

  • 能否提供数据和预期结果?
  • 所以数据列表看起来像这样:data = [0.5,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]。第一个索引看起来像:first_index = [7,17]。所以目前最终索引的预期结果应该是:second_index = [7,17]。如您所见,这是因为数据索引的第 7 个和第 17 个元素分别是 7 和 17,因此,虽然最初使用第一个索引可能看起来微不足道,但我希望能够在数据数组发生变化的情况。希望这个解释没问题?谢谢
  • 如果该答案有帮助,请告诉我。您的查询有点混乱,所以我会根据需要细化数据
  • 澄清一下,如果数据是data = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36],并且考虑到first_index = [7,17],那么我希望得到的结果是second_index = [14,34]。希望这能让事情更清楚一点?
  • @swag2198 是的,这是正确的,非常感谢您在下面的建议 - 效果很好!

标签: python arrays numpy for-loop indexing


【解决方案1】:

您可以直接使用numpy 数组进行索引:

>>> import numpy as np
>>> data = np.array([2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36])
>>> first_index = np.array([7, 17])
>>> second_index = data[first_index]
>>> second_index
array([16, 36])

【讨论】:

    【解决方案2】:
    ex= [0.5,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
    newarr=[]
    for i in range(len(ex)):
        newarr.append(ex[i])
    print(newarr) 
    
    [0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
    

    这是你要找的吗..?

    【讨论】:

    • 错误不完全,认为这只是将所有值从一个数组附加到另​​一个?我正在尝试使用数组通过使用第一个数组的元素索引数据集来从数据集中检索值。然后我想将这些检索到的值附加到一个新数组中。不过还是谢谢!
    猜你喜欢
    • 2023-03-31
    • 2023-01-30
    • 2018-09-25
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2013-07-30
    相关资源
    最近更新 更多