user11727742
user11727742

Reputation:

How to convert my variable to another using np.where

df['var']

a  start
a  start
b  middle
a  start
c  end

The code is working fine is below

conv = {'a': 'start', 'b':'middle', 'c':'end'}
df.var = df.var.map(conv)

Upvotes: 1

Views: 54

Answers (1)

jezrael
jezrael

Reputation: 863166

Your code is simpliest and working nice.

But it is possible with numpy.select:

df.var = np.select([df.var == 'a',df.var == 'b',df.var == 'c'], 
                    ['start','middle','end'], 
                    default=None) 

Or with 3 times numpy.where:

df.var = np.where(df.var == 'a', 'start',
         np.where(df.var == 'b', 'middle',
         np.where(df.var == 'c', 'end', None)))

Upvotes: 1

Related Questions