[英]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.在这里,我正在尝试使用.loc 从两列的总和创建一个新列“new”,但我无法创建它,它会在无效键中引发错误提示“W”。
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.您需要将两个 arguments 传递给 loc - 行和列。 So in your case it will be:
所以在你的情况下,它将是:
df['new'] = df.loc[:, 'W'] + df.loc[:, 'Y']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.