python - Converting an array of strings into an array of ones and zeros -
i have array looks this:
x = ['green', 'red', 'red', 'red', 'green', ...]
i want create new array y that:
y = [1, 0, 0, 0, 1, ...]
i have tried following , not work:
for n in x: if x[n] == 'red': p = 0 if x[n] == 'green': p = 1 y.append(p);
typeerror: list indices must integers, not str
you can create dictionary of desired mappings , map list
. more flexible if have lot of cases.
in [8]: x = ['green', 'red', 'red', 'red', 'green'] in [9]: d = {'green':1, 'red':0} in [10]: map(d.get, x) out[10]: [1, 0, 0, 0, 1]
Comments
Post a Comment