【问题标题】:Numpy Create array from irregular sized data [duplicate]Numpy从不规则大小的数据创建数组[重复]
【发布时间】:2018-09-21 10:08:42
【问题描述】:

我有不同大小的列表,例如

a = [1,2,3]
b = [4,5]

并且我想在短列表没有可用数据的地方创建一个包含这些值和默认值的二维数组。

c = do_something_with_a_b()
In: c 
Out: array([[1,2,3],
            [4,5, DEFAULT_VALUE]]) 

目前我使用以下内容,但我认为这过于复杂:

all_ar = []
all_ar.append(a)
all_ar.append(b)
# Get the size of all arrays for masking
len_ar = np.array([array.size for array in all_ar])
# Create a mask according to the length of the arrays
mask = np.arange(len_ar.max()) < len_ar[:,None]
# Create an array filled with the default value, here -1
c = np.full(mask.shape, -1, dtype='int')
# Use the mask to overwrite the the default values with the 
# data from the arrays 
c[mask] = np.concatenate(all_ar)
In: c
Out: array([[1,2,3],
            [4,5,-1]]) 

有没有更简单的方法可以将不规则大小的列表转换为具有规则形状和缺失数据点处的默认值的 numpy 数组?

【问题讨论】:

    标签: python numpy multidimensional-array


    【解决方案1】:

    您可以使用numpy 中的pad 函数:

    import numpy as np
    
    a = [[1,2,3], [4, 5]]
    
    # To what length do we need to pad?
    max_len = np.array([len(array) for array in a]).max()
    
    # What value do we want to fill it with?
    default_value = 0
    
    b = [np.pad(array, (0, max_len - len(array)), mode='constant', constant_values=default_value) for array in a]
    b
    

    代码在做什么?

    pad(0, max_len - len(array)) 参数表示我们要添加 0 列和 max_len - len(array) 行,以确保该数组与我们数据集中的最大数组匹配。

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 2020-02-25
      • 2014-07-09
      • 2013-06-26
      • 2015-08-31
      • 2021-06-29
      相关资源
      最近更新 更多