问题
my problem: I have a list of categorical variables such as
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 yields:
array([0, 0, 1, 1, 2, 2, 2])
and I want to turn into:
res = [0,0, 1,1, 0,0,0]
in essence, at every "switch", the number has to be switched from 1 to 0.
回答1:
First off, you can get the unique IDs
in a vectorized manner with np.unique and additional input argument return_inverse
-
c = np.unique(a,return_inverse=1)[1]
Then, use modulus(..,2)
to make the switches between 0
and 1
-
out = np.mod(c, 2) # Or c%2
回答2:
Maybe you are looking 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]
来源:https://stackoverflow.com/questions/40931910/turn-list-of-categorical-variables-into-0-1-list