Rotate the list of categorical variables in the (0,1) list

my problem: I have a list of categorical variables like

import numpy as np
a = np.array(['A','A','B','B','C','C','C'])
unique_vars = {v: k for k, v in enumerate(np.unique(a))}
c = np.array([unique_vars[i] for i in a])

which gives:

array([0, 0, 1, 1, 2, 2, 2])

and I want to include:

res = [0,0, 1,1, 0,0,0]

essentially, on each "switch" the number should be switched from 1 to 0.

+4
source share
2 answers

Firstly, you can get it unique IDsin vector form with the help of np.uniquean additional input argument return_inverse-

c = np.unique(a,return_inverse=1)[1]

Then use modulus(..,2)to switch between 0and 1-

out = np.mod(c, 2)  # Or c%2
+6
source

Perhaps you are looking at something like this:

arr = ['A','A','B','B','C','C','C']

def get_switched_array(in_array, value):
    return [ 1 if v == value else 0 for v in in_array ]

print get_switched_array( arr, 'A')
print get_switched_array( arr, 'B')
print get_switched_array( arr, 'C')

which outputs:

[1, 1, 0, 0, 0, 0, 0]
[0, 0, 1, 1, 0, 0, 0]
[0, 0, 0, 0, 1, 1, 1]
0
source

Source: https://habr.com/ru/post/1662631/


All Articles