【问题标题】:Adding zeroes at the end of an array based on the length the a Numpy Array Python根据 Numpy Array Python 的长度在数组末尾添加零
【发布时间】:2022-01-12 18:52:32
【问题描述】:

如果它们低于limit,我将如何创建一个在 numpy 数组末尾添加零的函数。所以下面的val数组会被转化为下面的Expected Outputs。

代码:

import numpy as np

val=np.array([1,4,11])

def Adjust(limit):
    #Funtion needed


Adjust(5)
Adjust(2)
Adjust(3)
Adjust(6)

预期输出:

[1,4,11,0,0]
[1,4,11]
[1,4,11]
[1,4,11,0,0,0]

【问题讨论】:

    标签: python numpy indexing format append


    【解决方案1】:
    def Adjust(arr, limit):
        if len(arr)<limit:
            return np.concatenate([arr, np.zeros(limit-len(arr), dtype = arr.dtype)])
        return arr
    

    【讨论】:

      【解决方案2】:
      val=np.array([1,4,11])
      
      def Adjust(limit):
          return np.concatenate([val, np.zeros(max(0, limit - len(val)))])
      
      def dbg(limit):
          print(Adjust(limit))
      
      dbg(5)
      dbg(2)
      dbg(3)
      dbg(6)
      
      • [0] * n 用 len n 创建一个零数组
      • a1 + a2 连接两个数组

      【讨论】:

      • 'val' 在您的代码中对我来说就像一个列表。而在 OP 的问题中,'val' 是一个 np 数组。 '[0]*n' 在我看来也像一个列表,而不是一个数组。 '+' 可以连接列表,但它不适用于 np 数组。尝试运行 'np.arange(3) + np.arange(5)' 看看你会得到什么。
      • 谢谢,你是对的,我更新了我的解决方案
      • 我认为在调用连接函数之前检查是否需要连接会更有效率。在你对 concat 的调用中,你调用 max,然后你调用 concat。如果 'val' 的长度低于 'limit',您可以通过仅调用 concat 来避免执行这种不必要的工作,而不是总是调用 concat。
      猜你喜欢
      • 2021-12-28
      • 2021-04-24
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2020-10-14
      • 2011-08-06
      • 1970-01-01
      相关资源
      最近更新 更多