[Numpy-discussion] strange behavior of variable

Eric Firing efiring at hawaii.edu
Sun Aug 18 04:27:00 EDT 2013


On 2013/08/17 9:49 PM, Sudheer Joseph wrote:
> Hi,
>           I have defined a small function to find the n maximum values
> of an array as below. With in it I assign the input array to a second
> array and temporarily make the array location after first iteration as
> nan. I expected this temporary change to be limited to the second
> variable. However my initial variable gets modified. Can any one through
> some light to what is happening here?. In case of matlab this logic works.
>
> ######
> #FUNCTION maxn
> ######
> import numpy as np
> def max_n(a,n):
>       b=a

This is not making "b" a copy of "a", it is simply making it an alias 
for it.  To make it a copy you could use "b = a[:]", or "b = a.copy()"

It sounds like you don't really need a function, however.  Try this:

# test data:
a = np.random.randn(10)
n = 2

# One-line solution:
biggest_n = np.sort(a)[-n:]

print a
print biggest_n

If you want them ordered from largest to smallest, just reverse the list:

biggest_n = biggest_n[::-1]

Eric


>       result=[]
>       for i in np.arange(1,n+1):
>           mxidx=np.where(b==max(b))
>           result.append(mxidx)
>           b[mxidx]=np.nan
>       result=np.ravel(result)
>       return(result)
>
> ### TEST
> In [8]: x=np.arange(float(0),10)
>
> In [9]: max
> max    max_n
>
> In [9]: max_n(x,2)
> Out[9]: array([9, 8])
>
> In [10]: x
> Out[10]: array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,  nan,  nan])
> ***************************************************************
> Sudheer Joseph
> Indian National Centre for Ocean Information Services
> Ministry of Earth Sciences, Govt. of India
> POST BOX NO: 21, IDA Jeedeemetla P.O.
> Via Pragathi Nagar,Kukatpally, Hyderabad; Pin:5000 55
> Tel:+91-40-23886047(O),Fax:+91-40-23895011(O),
> Tel:+91-40-23044600(R),Tel:+91-40-9440832534(Mobile)
> E-mail:sjo.India at gmail.com;sudheer.joseph at yahoo.com
> Web- http://oppamthadathil.tripod.com
> ***************************************************************
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>




More information about the NumPy-Discussion mailing list