Ragnar Lothbrok
Ragnar Lothbrok

Reputation: 1145

Most Efficient Way to Create New Column in Pandas from Existing One Based on Condition

How would I create a new column from an existing column based on condition? I know I can do it with a for loop, but it's very inefficient.

For example, let's say I have a column 'Customer_Left' with a binomial value of 0 or 1. I want to create a new column ('Value') that assigns a value of 100 to that customer.

My code was this:

value = 100

for i in range(len(df['Customer_Left')):
    if df['Customer_Left'][i] == 1:
        df['Value'] = value

What's the most efficient way to do this?

Upvotes: 0

Views: 45

Answers (1)

user3212593
user3212593

Reputation: 496

A more general answer if you want to set a value to a subset of rows is to use .loc with a condition, such as:

df.loc[df['Customer_Left'] == 1, 'Value'] = value

In your case, you could simply do:

df['Value'] = df['Customer_Left'] * 100

Upvotes: 2

Related Questions