[英]Flatten numpy array with python
Here is an example to reproduce my problem: 这是重现我的问题的示例:
a = np.array([[1,2], [3,4], [6,7]])
b = np.array([[1,2], [3,4], [6,7,8]])
c = np.array([[1,2], [3,4], [6]])
print(a.flatten())
print(b.flatten())
print(c.flatten())
The problem exist when one of the arrays has an item less or more. 当其中一个数组的项目较少或更多时,就会出现问题。
Output:
[1 2 3 4 6 7]
[list([1, 2]) list([3, 4]) list([6, 7, 8])] # Won't work
[list([1, 2]) list([3, 4]) list([6])] # Also won't work
How I want it:
[1 2 3 4 6 7]
[1 2 3 4 6 7 8]
[1 2 3 4 6]
Does anyone know how to flatten the list properly for example b and c? 有谁知道如何正确地平整列表,例如b和c?
Using concatenate
使用concatenate
np.concatenate(b)
Out[204]: array([1, 2, 3, 4, 6, 7, 8])
np.concatenate(c)
Out[205]: array([1, 2, 3, 4, 6])
You need: 你需要:
from itertools import chain
a = np.array([[1,2], [3,4], [6,7]])
b = np.array([[1,2], [3,4], [6,7,8]])
c = np.array([[1,2], [3,4], [6]])
print(a.flatten())
print(list(chain(*b)))
print(list(chain(*c)))
Output: 输出:
[1 2 3 4 6 7]
[1 2 3 4 6 7 8]
[1 2 3 4 6]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.