【问题标题】:How to modify rows of numpy arrays stored as a list如何修改存储为列表的numpy数组行
【发布时间】:2020-10-26 10:00:14
【问题描述】:

我想修改存储在列表中的 numpy 数组行。我的 numpy 数组的长度不一样。我有几个巨大的 numpy 数组存储为列表。这是我的数据(为简单起见,我只复制了一小部分数组):

elements= [array([[971, 466, 697, 1, 15, 18, 28],
                 [5445, 4, 301, 2, 12, 47, 5]]),
           array([[5883, 316, 377, 2, 9, 87, 1]])]

然后,我想用最后一列替换每一行的第四列,然后删除最后一列。我想得到以下结果:

[array([[971, 466, 697, 1, 28, 18],
        [5445, 4, 301, 2, 5, 47]]),
 array([[5883, 316, 377, 2, 1, 87]])]

我尝试了以下代码,但没有成功:

length=[len(i) for i in elements] # To find the length of each array
h=sum(length) # to find the total number of rows
for i in range (h):
    elements[:,[4,-1]] = elements[:,[-1,4]]
    elements=np.delete(elements,[-1],1)

我面临以下错误:

TypeError: list indices must be integers or slices, not tuple

提前感谢您的帮助。

【问题讨论】:

    标签: python arrays list numpy


    【解决方案1】:

    您可以在没有循环的情况下执行此操作,但它仍然比公认的解决方案慢(大数据的 1.75 倍):

    counts = list(map(len, elements))
    arr = np.concatenate(elements)
    arr[:, 4] = arr[:, -1]
    new_elements = np.split(arr[:,:-1], np.cumsum(counts)[:-1])
    

    numpy 的连接速度很慢。

    【讨论】:

      【解决方案2】:

      一个简单的低效解决方案:

      import numpy as np
      
      elements= [np.array([[971, 466, 697, 1, 15, 18, 28],
                           [5445, 4, 301, 2, 12, 47, 5]]),
                 np.array([[5883, 316, 377, 2, 9, 87, 1]])]
      
      new_elements = list()
      for arr in elements:
          arr[:, 4] = arr[:, -1]
          new_elements.append(arr[:, :-1])
      

      新的列表输出为:

      new_elements
      Out[11]: 
      [array([[ 971,  466,  697,    1,   28,   18],
              [5445,    4,  301,    2,    5,   47]]),
       array([[5883,  316,  377,    2,    1,   87]])]
      

      【讨论】:

      • 亲爱的@Mathieu,感谢您的解决方案。这正是我想要的。我很感激。
      【解决方案3】:

      试试这个

      p=[]
      for x in range(len(elements)):
          for y in range(len(elements[x])):
               p.append(list(elements[x][y][:4])+[elements[x][y][-1]]+[elements[x][y][-2]])
      print(p)
      
      [[971, 466, 697, 1, 28, 18],
      [5445, 4, 301, 2, 5, 47],
      [5883, 316, 377, 2, 1, 87]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-14
        • 1970-01-01
        • 2016-09-16
        • 2012-03-03
        • 2021-06-04
        • 2021-11-03
        • 2018-02-01
        • 2019-10-26
        相关资源
        最近更新 更多