将具有不同长度的列表列表转换为numpy数组 [英] Convert list of lists with different lengths to a numpy array

查看:1132
本文介绍了将具有不同长度的列表列表转换为numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,这些列表具有不同的长度(例如[[1, 2, 3], [4, 5], [6, 7, 8, 9]]),并希望将其转换为整数的numpy数组.我了解numpy多维数组中的子"数组必须具有相同的长度.那么将上述示例中的列表转换为像[[1, 2, 3, 0], [4, 5, 0, 0], [6, 7, 8, 9]]这样的numpy数组(即用零完成)的最有效方法是什么?

I have list of lists with different lengths (e.g. [[1, 2, 3], [4, 5], [6, 7, 8, 9]]) and want to convert it into a numpy array of integers. I understand that 'sub' arrays in numpy multidimensional array must be the same length. So what is the most efficient way to convert such a list as in example above into a numpy array like this [[1, 2, 3, 0], [4, 5, 0, 0], [6, 7, 8, 9]], i.e. completed with zeros?

推荐答案

您可以使用np.zeros创建一个numpy数组,并用列表元素填充它们,如下所示.

you could make a numpy array with np.zeros and fill them with your list elements as shown below.

a = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
import numpy as np
b = np.zeros([len(a),len(max(a,key = lambda x: len(x)))])
for i,j in enumerate(a):
    b[i][0:len(j)] = j

结果

[[ 1.  2.  3.  0.]
 [ 4.  5.  0.  0.]
 [ 6.  7.  8.  9.]]

这篇关于将具有不同长度的列表列表转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆