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 0 0 0 0 5 5 5 5 5 0 2 2 0 2 2 2 0 0 0 2 2 2 0 6 6 0 0 0 6 6 0 0 6 6]] 

As a first step i transformed all none 0 elements to 1 using this line :

 binary_transform = np.array(labels).astype(bool).astype(int) 

but i couldn't adjust that line to meet a different requirement as now i want to transform all the numbers except a given ones to 0, it may be 1 element, it may be all of them so i'll have to use a list let's say :

elements_to_keep = [2,4] 

so all the 1,3,5,6,7 will be transformed to 0 and i'll have the values of 4 and 2 in my matrix intact.

3 Answers 3

2

You can use numpy.isin:

data = numpy.arange(7) # array([0, 1, 2, 3, 4, 5, 6]) data[~numpy.isin(data, elements_to_keep)] = 0 # array([0, 0, 2, 0, 4, 0, 0]) 

As for binary_transform, instead of casting to bool and back you can also just assign the new values

data[data != 0] = 1 

or use numpy.sign

data = numpy.sign(data) 
Sign up to request clarification or add additional context in comments.

2 Comments

Got this error AttributeError: module 'numpy' has no attribute 'isin'.
@Nelly see this. You're using a version of numpy < 1.13
1

A solution which does not use numpy.isin:

def keep_only(data, to_keep): """ keep only the values in to_keep """ import numpy as np mask = np.zeros_like(data, dtype=bool) for elem in to_keep: mask[data==elem] = True return data * mask # testing import numpy as np data = np.random.randint(5, size=36).reshape(6,6) # use your data here elements_to_keep = [2,4] # use your values here new_data = keep_only(data, elements_to_keep) 

5 Comments

It's giving me None as output.
I just made sure to run this exact snippet by copying and pasting it into a pristine iPython shell, and it ran fine. I added an numpy import at the top to avoid any errors related to the np.random.randint call.
i tried it on the following labels = np.array([[0,1,2,3],[5,6,0,1,2],[2,3,4]])
What is labels supposed to be? The elements to keep?
That is no matrix. It has a varying number of elements per row. Is that supposed to be a sparse matrix?
1

You can use pd.DataFrame and applymap for filtering elementwise

import pandas as pd values_to_keep = [2,4] df = pd.DataFrame(data).applymap(lambda x: 1 if x in values_to_keep else 0) data = df.values 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.