简体   繁体   English

在python中删除numpy数组中的行

[英]delete rows in numpy array in python

I have an array and I want to delete some rows according to a criteria. 我有一个数组,我想根据条件删除一些行。 The criteria is if a row has all elements as zero other than the first element, it should be deleted. 条件是,如果一行中除第一个元素外所有元素均为零,则应将其删除。 So if tempn has only '0', that row is deleted. 因此,如果tempn只有'0',则删除该行。 Consider this for narrays and ntemps (that is., no fixed rows or arrays) 对于narrays和ntemps考虑这一点(也就是说,没有固定的行或数组)

my_input = [array([['temp1', '32F'],
   ['temp2', '243K'],
   ['temp3', '0'],
   ['temp4', '0'],
   ['temp5', '0'],
   ['temp6', '30C'],
   ['temp7', '0'],
   ['temp8', '15C'],
   ['temp9', '0'],
   ['temp10', '-17C']], 
  dtype='|S2'), array([['temp1', '110F'],
   ['temp2', '44C'],
   ['temp3', '0'],
   ['temp4', '0'],
   ['temp5', '300K'],
   ['temp6', '0'],
   ['temp7', '0'],
   ['temp8', '465R'],
   ['temp9', '0'],
   ['temp10', '0']], 
  dtype='|S2'), array([['temp1', '0'],
   ['temp2', '0', '0'],
   ['temp3', '91F', '0'],
   ['temp4', '14C', '284K'],
   ['temp5', '260K', '0'],
   ['temp6', '-10C', '458R'],
   ['temp7', '0', '0'],
   ['temp8', '-1C', '12F'],
   ['temp9', '0', '96F'],
   ['temp10', '0', '0']], dtype='|S2')]

  my_output = [array([['temp1', '32F'],
   ['temp2', '243K'],
   ['temp6', '30C'],
   ['temp8', '15C'],
   ['temp10', '-17C']], 
  dtype='|S2'), array([['temp1', '110F'],
   ['temp2', '44C'],
   ['temp5', '300K'],
   ['temp8', '465R']],
  dtype='|S2'), array([['temp1', '0', '423R'],
   ['temp3', '91F', '0'],
   ['temp4', '14C', '284K'],
   ['temp5', '260K', '0'],
   ['temp6', '-10C', '458R'],
   ['temp8', '-1C', '12F'],
   ['temp9', '0', '96F']], dtype='|S2')]

I tried 我试过了

    for columns in my_input:
         for rows in columns:
             for elements in rows:
                if rows[1]&rows[2]==0|rows[1]&rows[2]&rows[3]==0:
                   my_output = np.delete(my_input,(rows[1]),axis=0)

Couldnt figure for n rows. 无法显示n行。 Can anyone show how to accomplish this? 谁能展示如何做到这一点?

In your proposed solution you are comparing with the integer 0, but the arrays consists of strings. 在您提出的解决方案中,您正在与整数0进行比较,但是数组由字符串组成。 So rows[1] == 0 will always give False . 因此,rows [1] == 0将始终为False There's other things wrong with your solution as well. 您的解决方案也存在其他问题。

Putting that aside, here's something that should work: 抛开这些,这应该是可行的:

output = []
for C in my_input:
    mask = ~np.all(C[:, 1:] != '0', axis=1)
    output.append(C[mask])

Note that ~ stands for elementwise negation. 请注意,〜表示元素取反。

A oneliner for this would be 一个oneliner将是

output = [C[~np.all(C[:, 1:] != '0', axis=1)] for C in my_input]

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

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