Tamer Jabsheh
Tamer Jabsheh

Reputation: 21

Creating new column in Pandas based on values from another column

The task is the following:

Add a new column to df called income10. It should contain the same values as income with all 0 values replaced with 1.

I have tried the following code:

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

but I keep getting an error:

enter image description here

Upvotes: 2

Views: 68

Answers (2)

Fruity Medley
Fruity Medley

Reputation: 564

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. Try this instead

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

Edit: corrected order of arguments

Upvotes: 0

adnanmuttaleb
adnanmuttaleb

Reputation: 3604

You can apply a function on each value in your column:

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

Upvotes: 1

Related Questions