Python:上下对齐布尔型numpy数组的索引 [英] Python: up and down justify the index of a bool numpy array

查看:132
本文介绍了Python:上下对齐布尔型numpy数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何上下对齐一个numpy bool数组.称谓是指取True值并将其移动,以便它们成为顶部的第一个值(如果它们是向上对齐的)或底部的第一个值. (如果它们没有正当理由)

How can I up and down justify a numpy bool array. By Justify, I mean take the True values, and move them so they are either the first values at the top (if they are up justified) or the first values at the bottom. (if they are down justified)

    [[False  True  True  True  True   True]
     [False  False True  True  False  True]
     [False  True  False True  False  False
     [True   True  True  True  False  True]]

因此,如果我向下证明上面显示的bool数组的True值是合理的,则它看起来像:

So If I down justify the True values of the bool array shown above, it would look like:

[[False  False False True  False False]
 [False  True  True  True  False True]
 [False  True  True  True  False True]
 [True   True  True  True  True  True]]

推荐答案

在每一列中对其进行简单排序,这会推低True值,而出现False则是向下对齐的版本.对于向上对齐的版本,请对已排序的版本进行翻转.

Simply sort it along each column, which pushes down the True values, while brings up the False ones for down-justified version. For up-justified one, do a flipping on the sorted version.

运行示例以展示实现-

In [216]: mask
Out[216]: 
array([[False,  True,  True,  True,  True,  True],
       [False, False,  True,  True, False,  True],
       [False,  True, False,  True, False, False],
       [ True,  True,  True,  True, False,  True]], dtype=bool)

In [217]: np.sort(mask,0)  # Down justified
Out[217]: 
array([[False, False, False,  True, False, False],
       [False,  True,  True,  True, False,  True],
       [False,  True,  True,  True, False,  True],
       [ True,  True,  True,  True,  True,  True]], dtype=bool)

In [218]: np.sort(mask,0)[::-1]   # Up justified
Out[218]: 
array([[ True,  True,  True,  True,  True,  True],
       [False,  True,  True,  True, False,  True],
       [False,  True,  True,  True, False,  True],
       [False, False, False,  True, False, False]], dtype=bool)

这篇关于Python:上下对齐布尔型numpy数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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