numpy 如何动态地将十进制数转换为整数

iyfamqjs  于 2023-03-12  发布在  其他
关注(0)|答案(4)|浏览(131)

我有如下数据:

a = np.array([[61.22, 92.92, -53.0],
              [-0.272, 0.2828, -0.737],
              [12.43, -0.732, 0.82],
              [52.1, -62.12, 37.78],
              [0.1, 0.67, -0.22],
              [-0.09, -0.28, 0.22],
              [82.1, -11.12, 45.78],
              [-52.1, 0.12, -37.78]])

如果数组中的索引1-3包含数字== 0,则我希望将其更改为0。
预期结果如下:

a = np.array([[61.22, 92.92, -53.0],
              [0.,0., 0.],
              [12.43, -0.732, 0.82],
              [52.1, -62.12, 37.78],
              [0., 0., 0.],
              [0., 0., 0.],
              [82.1, -11.12, 45.78],
              [-52.1, 0.12, -37.78]])

我尝试使用简单的代码,但它不工作:

for i in range(len(a)):
  if a[i].all()==0:
    a[i] = np.round(a[i],0)
ohfgkhjo

ohfgkhjo1#

实际上,您希望检查数字是否以0开头,即它们的绝对值是否小于1。在这种情况下,您可以用途:

for i in range(len(a)):
    if (np.abs(a[i]) < 1).all():
        a[i] = 0
t0ybt7op

t0ybt7op2#

给你:

a = np.array([[61.22,92.92,53.0],
             [-0.272,0.2828,-0.737],
             [12.43,-0.732,0.82],
             [52.1,62.12,37.78],
             [0.1,0.67,-0.22],
             [-.09,-0.28,0.22],
             [82.1,11.12,45.78],
             [52.1,0.12,37.78]])

a[np.all(np.abs(a) < 1, axis=1), :] = 0

# a is now:
#
# array([[61.22 , 92.92 , 53.   ],
#       [ 0.   ,  0.   ,  0.   ],
#       [12.43 , -0.732,  0.82 ],
#       [52.1  , 62.12 , 37.78 ],
#       [ 0.   ,  0.   ,  0.   ],
#       [ 0.   ,  0.   ,  0.   ],
#       [82.1  , 11.12 , 45.78 ],
#       [52.1  ,  0.12 , 37.78 ]])

您的问题是,您正在检查if a[i].all()==0:,但您想要的是行中所有小于1的数字的绝对值。

p5cysglq

p5cysglq3#

也许你可以这样做:

import numpy as np

a = np.array([[61.22,92.92,53.0],
                 [-0.272,0.2828,-0.737],
                 [12.43,-0.732,0.82],
                 [52.1,62.12,37.78],
                 [0.1,0.67,-0.22],
                 [-.09,-0.28,0.22],
                 [82.1,11.12,45.78],
                 [52.1,0.12,37.78]])

for i in range(len(a)):
   all_zero: bool = True
   
   for j in range(len(a[i])):
        num_str: str = str(a[i][j])
        first_digit: int = int(num_str[1] if num_str[0] == '-' else num_str[0])
        if first_digit == 0:
            all_zero = True
        else:
            all_zero = False
            break
   
   if all_zero:
       for j in range(len(a[i])):
           a[i][j] = 0
    

print(a)

它检查每个数组及其每个元素。如果数组中每个项的第一个实际数字为零,则将数组的每个元素设置为零。

czq61nw1

czq61nw14#

必须将else-0.737舍入为1.0

a[np.all( np.where(np.trunc(a)==0,True,False),axis=1)]=0

相关问题