本文介绍了在一维 NumPy 数组中翻转零和一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个一维的 NumPy 数组,它由零和一个组成,如下所示:

I have a one-dimensional NumPy array that consists of zeroes and ones like so:

array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

我想要一种快速的方法来翻转"值,使零变为一,一变为零,从而产生一个像这样的 NumPy 数组:

I'd like a quick way to just "flip" the values such that zeroes become ones, and ones become zeroes, resulting in a NumPy array like this:

array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

有没有一个简单的单线?我查看了 fliplr() 函数,但这似乎需要二维或更大维度的 NumPy 数组.我敢肯定有一个相当简单的答案,但任何帮助将不胜感激.

Is there an easy one-liner for this? I looked at the fliplr() function, but this seems to require NumPy arrays of dimensions two or greater. I'm sure there's a fairly simple answer, but any help would be appreciated.

推荐答案

你的 Q 中一定有我不明白的地方...

There must be something in your Q that i do not understand...

无论如何

In [2]: from numpy import array

In [3]: a = array((1,0,0,1,1,0,0))

In [4]: b = 1-a

In [5]: print a ; print b
[1 0 0 1 1 0 0]
[0 1 1 0 0 1 1]

In [6]: 

这篇关于在一维 NumPy 数组中翻转零和一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 13:48