简体   繁体   English

无法从现有的两个列在 Pandas dataframe 中创建新列

[英]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.

相关问题 使用 pandas/python 从 DataFrame 中的两个现有文本列创建一个新列 - Create a new column from two existing text columns in a DataFrame using pandas/python Pandas:使用从预先存在的列计算的值在数据框中创建两个新列 - Pandas: create two new columns in a dataframe with values calculated from a pre-existing column 从现有数据框列创建新数据框 - Make new dataframe from existing dataframe columns 根据其他列 ID 从现有 dataframe 中获取新 pandas dataframe 中的汇总数据列 - Get summary data columns in new pandas dataframe from existing dataframe based on other column-ID Pandas:如何使用现有字符串数据列在 dataframe 中创建两个新列 - Pandas: how to create two new columns in a dataframe with an existing string data column 从现有数据框中创建新数据框,其中一列中的唯一值和其他列中的对应值 - Make new dataframe from existing dataframe with unique values from one column and corresponding values from other columns 如何将两个数据帧中的两列合并为一个新数据帧(pandas)的一列? - How to merge the two columns from two dataframe into one column of a new dataframe (pandas)? Python Pandas从现有列和另一个数据框中的数据创建新列 - Python pandas make new column from data in existing column and from another dataframe 从现有 dataframe 的某些列创建新的 pandas dataframe - Creating new pandas dataframe from certain columns of existing dataframe 从现有列构造新列,而无需在pandas中重新指定数据框 - Construct new column from existing columns without re specifying dataframe in pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM