# [Numpy-discussion] Unique() function and avoiding Loop

Aronne Merrelli aronne.merrelli at gmail.com
Wed Jul 10 14:11:07 EDT 2013

```On Fri, Jul 5, 2013 at 4:20 AM, Bakhtiyor Zokhidov <
bakhtiyor_zokhidov at mail.ru> wrote:

> Hi everybody,
>
> I have a problem with sorting out the following function. What I expect is
> that I showed as an example below.
>
> Two problems are encountered to achieve the result:
> 1) The function sometimes can't not sort as expected: I showed an example
> for that below.
> 2) I could not do vectorization to avoid loop.
>
>
> OR, Is there another way to solve that problem??
>
>
> Example:
> data = ['', 12, 12, 423, '1', 423, -32, 12, 721, 345]. Expected
> result:  [0, 12, 12, 423, 0, 423, -32, 12, 721, 345], here, '' and '1'
> are string type I need to replace them by zero
>

I don't understand your code example, but if your problem is fully
described as above (replace the strings '' or '1' with the integer 0), then
it would seem simplest to just do this with python built in functions
rather than using numpy. The numpy functions work best with arrays, and
your "data" variable is a python list with a mixture of integers and
strings.

Here is a possible solution:

>>> data = ['', 12, 12, 423, '1', 423, -32, 12, 721, 345]
>>> foo = lambda x: 0 if (x == '') or (x == '1') else x
>>> print map(foo, data)
[0, 12, 12, 423, 0, 423, -32, 12, 721, 345]

Hope that helps,
Aronne

> The result I got: ['', 12, 12, 423, '1', 423, -32, 12, 721, 345]
>
> import numpy as np
>
> def func(data):
>
>           x, i = np.unique(data, return_inverse = True)
>           f = [ np.where( i == ind ) for ind in range(len(x)) ]
>
>           new_data = []
>           # Obtain 'data' arguments and give these data to New_data
>           for i in range(len(x)):
>                       if np.size(f[i]) > 1:
>                                  for j in f[i]:
>                                          if str(data[j]) <> '':
>
> new_data.append(data[j])
>                                               else:
>                                                     data[j] = 0
>           return data
>
> --
> Bakhtiyor Zokhidov
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20130710/580318a3/attachment.html>
```