删除numpy数组中的行 [英] deleting rows in numpy array

查看:196
本文介绍了删除numpy数组中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数组:

I have an array that might look like this:

ANOVAInputMatrixValuesArray = [[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 
0.53172222], [ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]]

请注意,其中一行的结尾处为零.我想删除任何包含零的行,同时保留所有单元格中包含非零值的任何行.

Notice that one of the rows has a zero value at the end. I want to delete any row that contains a zero, while keeping any row that contains non-zero values in all cells.

但是该数组每次填充时的行数都会不同,并且零每次都将位于不同的行中.

But the array will have different numbers of rows every time it is populated, and the zeros will be located in different rows each time.

我用下面的代码行获得每行中非零元素的数量:

I get the number of non-zero elements in each row with the following line of code:

NumNonzeroElementsInRows    = (ANOVAInputMatrixValuesArray != 0).sum(1)

对于上面的数组,NumNonzeroElementsInRows包含:[5 4]

For the array above, NumNonzeroElementsInRows contains: [5 4]

五个表示第0行中的所有可能值都不为零,而四个表示第1行中的所有可能值之一为零.

The five indicates that all possible values in row 0 are nonzero, while the four indicates that one of the possible values in row 1 is a zero.

因此,我正在尝试使用以下代码行来查找和删除包含零值的行.

Therefore, I am trying to use the following lines of code to find and delete rows that contain zero values.

for q in range(len(NumNonzeroElementsInRows)):
    if NumNonzeroElementsInRows[q] < NumNonzeroElementsInRows.max():
        p.delete(ANOVAInputMatrixValuesArray, q, axis=0)

但是由于某种原因,即使执行许多打印命令表明所有变量似乎都正确地填充了代码,该代码似乎也无能为力.

But for some reason, this code does not seem to do anything, even though doing a lot of print commands indicates that all of the variables seem to be populating correctly leading up to the code.

必须有一些简单的方法来简单地删除包含零值的任何行."

There must be some easy way to simply "delete any row that contains a zero value."

任何人都可以告诉我编写什么代码来完成此任务吗?

Can anyone show me what code to write to accomplish this?

推荐答案

从数组中删除行和列的最简单方法是numpy.delete方法.

The simplest way to delete rows and columns from arrays is the numpy.delete method.

假设我有以下数组x:

x = array([[1,2,3],
        [4,5,6],
        [7,8,9]])

要删除第一行,请执行以下操作:

To delete the first row, do this:

x = numpy.delete(x, (0), axis=0)

要删除第三列,请执行以下操作:

To delete the third column, do this:

x = numpy.delete(x,(2), axis=1)

因此,您可以找到其中包含0的行的索引,将它们放在列表或元组中,并将其作为函数的第二个参数传递.

So you could find the indices of the rows which have a 0 in them, put them in a list or a tuple and pass this as the second argument of the function.

这篇关于删除numpy数组中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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