Reputation:
Here, I'm trying to create a new column 'new' from the sum of two columns using .loc, but I'm unable to create it, it throws an error saying 'W' in invalid key.
This works
df['new'] = df['W'] + df['Y']
This is not working
df = pd.DataFrame([[1.0,5.0,1],[2,np.NaN,2],[np.NaN,np.NaN,3]], columns = ['W','Y','Z'])
df['new'] = df.loc['W'] + df.loc['Y']
Upvotes: 0
Views: 185
Reputation: 567
You need to pass two arguments to loc - row and column. So in your case it will be:
df['new'] = df.loc[:, 'W'] + df.loc[:, 'Y']
Upvotes: 1