Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于另一列的值在Pandas中创建新列_Python_Pandas - Fatal编程技术网

Python 基于另一列的值在Pandas中创建新列

Python 基于另一列的值在Pandas中创建新列,python,pandas,Python,Pandas,任务如下: 向df添加一个名为income10的新列。它应该包含相同的内容 值作为收入,所有0值替换为1 我尝试了以下代码: df['income10'] = np.where(df['income']==0, df['income10'],1) 但我不断地得到一个错误: 您可以对列中的每个值应用函数: df["a"] = df.a.apply(lambda x: 1 if x == 0 else x) 您正在尝试引用一个尚不存在的列 df['income10'] = np.where(df

任务如下:

向df添加一个名为income10的新列。它应该包含相同的内容 值作为收入,所有0值替换为1

我尝试了以下代码:

df['income10'] = np.where(df['income']==0, df['income10'],1)
但我不断地得到一个错误:


您可以对列中的每个值应用函数:

df["a"] = df.a.apply(lambda x: 1 if x == 0 else x)

您正在尝试引用一个尚不存在的列

df['income10'] = np.where(df['income']==0, ===>**df['income10']**,1)
在np.where中,您需要引用值产生的列。试试这个

df['income10'] = np.where(df['income']==0, 1, df['income'])

编辑:更正了参数顺序

有什么错误?@Groger刚刚用error的图像更新了帖子似乎income不是有效的列名。如果您打印出df.columns,您应该能够看到哪些列对您可用。他希望将新值分配给新列我认为您的where是向后的。它应该是
df['income10']=np.where(df['income']==0,1,df['income'])
如果为真则为1,否则
df['income]
@DavidBuck
np.where
np.where(boolArray,trueValues,false)
Yep,OP表示“0值替换为1”,所以当
df['income]=0
为真时,它应该为1,否则,
df['income']
@DavidBuck我明白我的错误了。谢谢你抓住它。