python上下对齐,Python:上下对齐布尔型numpy数组的索引

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]]

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]]

解决方案

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.

Sample run to showcase the implementation -

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值