简体   繁体   English

在列块中展平或分组数组 - NumPy / Python

[英]Flatten or group array in blocks of columns - NumPy / Python

Is there any easy way to flatten有什么简单的方法可以压扁

import numpy    
np.arange(12).reshape(3,4)
Out[]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

into进入

array([ 0,  1,  4,  5, 8, 9, 2, 3, 6, 7, 10, 11])

It seems like you are looking to consider a specific number of cols to form blocks and then getting the elements in each block and then moving onto the next ones.似乎您正在考虑考虑特定数量的 cols 来形成块,然后获取每个块中的元素,然后移动到下一个块。 So, with that in mind, here's one way -因此,考虑到这一点,这是一种方法 -

In [148]: a
Out[148]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [149]: ncols = 2 # no. of cols to be considered for each block

In [150]: a.reshape(a.shape[0],-1,ncols).swapaxes(0,1).ravel()
Out[150]: array([ 0,  1,  4,  5,  8,  9,  2,  3,  6,  7, 10, 11])

The motivation behind is discussed in detail in this post . this post详细讨论了背后的动机。

Additionally, to keep the 2D format -此外,为了保持 2D 格式 -

In [27]: a.reshape(a.shape[0],-1,ncols).swapaxes(0,1).reshape(-1,ncols)
Out[27]: 
array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [ 2,  3],
       [ 6,  7],
       [10, 11]])

And to have it in a intuitive 3D array format -并以直观的 3D 数组格式拥有它 -

In [28]: a.reshape(a.shape[0],-1,ncols).swapaxes(0,1)
Out[28]: 
array([[[ 0,  1],
        [ 4,  5],
        [ 8,  9]],

       [[ 2,  3],
        [ 6,  7],
        [10, 11]]])

For this I'd simply slice and concatenate :为此,我只需切片和concatenate

n = a.shape[1]//2
np.concatenate([a[:,:n], a[:,n:]]).ravel()
# array([ 0,  1,  4,  5,  8,  9,  2,  3,  6,  7, 10, 11])

You can use a list comprehension to slice the array into blocks and then use the numpy.ndarray.flatten method to flatten the blocks into a 1D array (this will only work if a.shape[1] is divisible by the block size n ):您可以使用列表推导将数组分割成块,然后使用numpy.ndarray.flatten方法将块展平为一维数组(这仅在a.shape[1]可被块大小n整除时才有效) :

import numpy as np

a = np.arange(12).reshape(3, 4)

n = 2

res = np.array([a[:, i : i + n] for i in range(0, a.shape[1], n)]).flatten()

print(res)

Output: Output:

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

Another way:另一种方式:

first_list = [entry[0:2] for entry in a]
second_list = [entry[2:4] for entry in a]
flat_list = [item for sublist in first_list for item in sublist] + [item for sublist in second_list for item in sublist]

flat_list # [0, 1, 4, 5, 8, 9, 2, 3, 6, 7, 10, 11]

I have a solution that doesn't involve numpy if you want, and it will take care for every kind of array you'll get,如果你愿意,我有一个不涉及 numpy 的解决方案,它会照顾你得到的每一种阵列,

[[12312],[],[[]]] 
[[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]
[-1, [1, [-2], 1], -1]
etc

First option(won't work for strings )第一个选项(不适用于字符串

def flat_list(array):
    return list(flatten(array))              
def flatten(nested): 
    try:
        for sublist in nested:
            for element in flatten(sublist):
                yield element
    except TypeError:
        yield nested

Second option:第二种选择:

def flatten(nested): #in case you got strings and you want to avoide an infinite recursion
    try:
        # Don't iterate over string-like objects:
        try: nested + ''
        except TypeError: pass
        else: raise TypeError
        for sublist in nested:
            for element in flatten(sublist):
                yield element
    except TypeError:
        yield nested

You are using numpy here.您在这里使用 numpy。 It has a method to do exactly what you want.它有一种方法可以完全按照您的意愿行事。

import numpy as np

arr = np.arange(12).reshape(3,4)
flat = arr.flatten()

Another approach:另一种方法:

a = []
[a.extend(x) for x in arr]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM