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 0 6 6]
     [0 1 1 0 0 0 0 0 0 7 0 0 0 3 3 0 0 0 4 4 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.

Upvotes: 0

Views: 84

Answers (3)

Stella Yang
Stella Yang

Reputation: 11

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

Upvotes: 1

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5935

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)

Upvotes: 1

Nils Werner
Nils Werner

Reputation: 36765

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)

Upvotes: 2

Related Questions