如何打印数组的百分比?
例如:
如果我有一个数组:
x = np.array([2,3,1,0,4,3,5,4,3,2,3,4,5,10,15,120,102,10])
如何将数组的一部分设置为零?如果我想保留数组的前10%不变,并将剩余的90%更改为零,应该怎么做呢?
提前谢谢您。
这将在前面大致给你90%的结果:
x[0:int(len(x)*0.9)]
背面的90%(通过跳过前10%):
x[int(len(x)*0.1):]
因此,要将最后的90%设置为零:
x[int(len(x)*0.1):] = 0
x[(len(x)*0.1):] = 0
。 - daniel451x[len(x)*0.1:] = 0
会抛出一个错误:TypeError: 只能分配可迭代对象
。 - levilen(x)*0.1
的结果转换为int
,然后再使用它。 - Simon Gibbonsimport numpy as np
x = np.array([2,3,1,0,4,3,5,4,3,2,3,4,5,10,15,120,102,10])
cut_off = int(0.1*len(x))
print(len(x), cut_off)
for idx in range(cut_off,len(x)):
x[idx] = 0
x = [2,3,1,0,4,3,5,4,3,2,3,4,5,10,15,120,102,10]
index = 10 * len(x) / 100
x[index:] = [0]*(len(x) - 1 index )
print x
>>> x = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Here is what I would do:
x = np.array([2,3,1,0,4,3,5,4,3,2,3,4,5,10,15,120,102,10])
change = round(0.9 * len(x)) # changing 90%
x[-change:] = 0 # change from last value towards beginning of array
print(x)
yielding
[2 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
做这个工作吗?
x = np.array([2,3,1,0,4,3,5,4,3,2,3,4,5,10,15,120,102,10])
j=len(x)
k=(j/100)*10
for index in range(k,j):
x[index]=0