Reputation: 44
This is the current code I use to move one column's value for a certain row to another column for the same row:
#Move 2014/15 column ValB to column ValA
df.loc[(df.Survey_year == 2014), 'ValA'] = df.loc[(df.Survey_year == 2014), 'ValB']
I do the same .loc[] again except on 2015 too. This works, but I don't think this is the most efficient way to do it if I'm using a big data frame with a lot of values to do this for.
Upvotes: 2
Views: 11237
Reputation: 7903
Its similiar but much simpler logic. np.where
allows you to define an if statement similar excel. If(x=y, do this is true, do this if false).
import numpy as np
df['ValA'] = np.where((df.Survey_year == 2014) | (df.Survey_year == 2015), df['ValB'], df['ValA'])
Upvotes: 5
Reputation: 294358
Clean Option
mask = df.Survey_year.isin([2014, 2015])
df.loc[mask, 'ValA'] = df.loc[mask, 'ValB']
Fast Option
mask = np.in1d(df.Survey_year.values, [2014, 2015])
bloc = df.index.get_loc('ValB')
v = df.values
df.loc[mask, 'ValA'] = v[mask, bloc]
Upvotes: 5