简体   繁体   中英

Unable to make a new column in Pandas dataframe from two existing columns

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'] 

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'] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM