如何使用两个列表推导创建2d numpy ndarray [英] How to create a 2d numpy ndarray using two list comprehensions

查看:90
本文介绍了如何使用两个列表推导创建2d numpy ndarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码创建2D numpy ndarray:

I tried to create a 2D numpy ndarray using the following code:

temp = np.array([[np.mean(w2v[word]) for word in docs if word in w2v] for docs in X[:5]])

temp的形状为(5,)而不是预期的(5,x).

temp has a shape of (5,) instead of expected (5,x).

临时的数据结构也类似于:array([list([.....],...)])

Also temps's data structure is like: array([list([.....],...)])

内部列表似乎没有转换为ndarray.

It seems that the inner list is not converted to ndarray.

推荐答案

您在那里缺少的np.array应该是:

Your missing np.array in there, it should be:

temp = np.array([np.array([np.mean(w2v[word]) for word in docs if word in w2v] for docs in X[:5])])

运行示例:

bob
Out[70]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

tmp = np.array([np.array([x for x in Y]) for Y in bob])

tmp
Out[72]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

这篇关于如何使用两个列表推导创建2d numpy ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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