在python中复制以前的输入,如果小于零

时间:2022-09-06 20:06:52

I have written a python code to duplicate the previous input if any entry is less than zero or nan except the first row in a matrix. But it is not working as I need what is the possible error I am doing and is there any other efficient way to do this without using multiple for loops. The input matrix values may be differ in some case and may contain float values.

我编写了一个python代码来复制前面的输入,如果任何条目小于零或nan,除了矩阵中的第一行。但是它不能工作,因为我需要我正在做的可能的错误,是否有其他有效的方法可以不使用多个for循环。在某些情况下,输入矩阵的值可能不同,可能包含浮点值。

import numpy as np
from math import isnan
data = [[0, -1, 2],
        [7,8.1,-3],
        [-8,5, -1],
        ['N',7,-1]]
m, n = np.shape(data)

for i in range (1,m):
 for j in range (n):
  if data[i][j] < 0 or isnan:
   data[i][j] = data[i-1][j]

print data

The expected output is

预期的输出

[[0,-1,2],
 [7,8.1,2],
 [7,5,2],
 [7,7,2]]

But, I am getting

但是,我得到

[[0, -1, 2],
 [0, -1, 2],
 [0, -1, 2],
 [0, -1, 2]]

1 个解决方案

#1


2  

You're saying if data[i][j] < 0 or isnan:. isnan is a function, and will always make the if statement True. You would want isnan(data[i][j]). But in this case, it looks like what you want to check is if not isinstance(data[i][j], (int, float)).

你说的是if data[i][j] < 0或isnan:。isnan是一个函数,它总是使if语句为真。你希望isnan(数据[我][j])。但是在这种情况下,看起来您想要检查的是if非isinstance(data[i][j], (int, float))。

import numpy as np

data = [
    [0, -1, 2],
    [7, 8, -3],
    [-8, 5, -1],
    ['N', 7, -1]
    ]
m, n = np.shape(data)

for i in range(1, m):
    for j in range(n):
        if data[i][j] < 0 or not isinstance(data[i][j], (int, float)):
            data[i][j] = data[i-1][j]

for row in data:
    print row

Output:

输出:

[0, -1, 2]
[7, 8, 2]
[7, 5, 2]
[7, 7, 2]

#1


2  

You're saying if data[i][j] < 0 or isnan:. isnan is a function, and will always make the if statement True. You would want isnan(data[i][j]). But in this case, it looks like what you want to check is if not isinstance(data[i][j], (int, float)).

你说的是if data[i][j] < 0或isnan:。isnan是一个函数,它总是使if语句为真。你希望isnan(数据[我][j])。但是在这种情况下,看起来您想要检查的是if非isinstance(data[i][j], (int, float))。

import numpy as np

data = [
    [0, -1, 2],
    [7, 8, -3],
    [-8, 5, -1],
    ['N', 7, -1]
    ]
m, n = np.shape(data)

for i in range(1, m):
    for j in range(n):
        if data[i][j] < 0 or not isinstance(data[i][j], (int, float)):
            data[i][j] = data[i-1][j]

for row in data:
    print row

Output:

输出:

[0, -1, 2]
[7, 8, 2]
[7, 5, 2]
[7, 7, 2]