简体   繁体   中英

How to display a percentage of an Array in python

How would you print out a percentage of an array?

For example:

if i had

x = np.array([2,3,1,0,4,3,5,4,3,2,3,4,5,10,15,120,102,10])

How would you set a percentage of the array to zero? if I wanted to keep the first 10% of an array as it is and change the remaining 90% of the array to zeros?

Thank you in advance?

This will give you roughly 90% at the front:

x[0:int(len(x)*0.9)]

And 90% at the back (by skipping the first 10%):

x[int(len(x)*0.1):]

So to set the last 90% to zero:

x[int(len(x)*0.1):] = 0

You could do like this:

import 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]

do this work?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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