简体   繁体   English

根据另一列的值在 Pandas 中创建新列

[英]Creating new column in Pandas based on values from another column

The task is the following:任务如下:

Add a new column to df called income10.向 df 添加一个名为income10 的新列。 It should contain the same values as income with all 0 values replaced with 1.它应该包含与收入相同的值,并将所有 0 值替换为 1。

I have tried the following code:我尝试了以下代码:

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

but I keep getting an error:但我不断收到错误消息:

在此处输入图像描述

You can apply a function on each value in your column:您可以对列中的每个值应用 function:

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

You are trying to reference a column which does not exist yet.您正在尝试引用一个尚不存在的列。

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

In your np.where, you need to reference the column where the values originate.在您的 np.where 中,您需要引用值所在的列。 Try this instead试试这个

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

Edit: corrected order of arguments编辑:更正了 arguments 的顺序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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