al exx
al exx

Reputation: 75

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?

Upvotes: 3

Views: 7977

Answers (5)

John Zwinck
John Zwinck

Reputation: 249263

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

Upvotes: 12

Shawn Mehan
Shawn Mehan

Reputation: 4568

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]

Upvotes: 1

levi
levi

Reputation: 22697

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]

Upvotes: 1

milevyo
milevyo

Reputation: 2180

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

Upvotes: 0

Marcin
Marcin

Reputation: 238299

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

Upvotes: 2

Related Questions