Home > Backend Development > Python Tutorial > How to Create a New Column with Condition-Based Values in Pandas?

How to Create a New Column with Condition-Based Values in Pandas?

Barbara Streisand
Release: 2024-12-22 16:56:10
Original
496 people have browsed it

How to Create a New Column with Condition-Based Values in Pandas?

Creating a New Column with Condition-Based Values

This question explores how to add a new column, color, to a given dataframe. The condition is that color should be set to 'green' if the corresponding value in the Set column is 'Z' and 'red' otherwise.

Solution with Numpy Where:

For scenarios with only two choices, the np.where method can be utilized. Here's the code:

1

df['color'] = np.where(df['Set'] == 'Z', 'green', 'red')

Copy after login

This approach effectively assigns 'green' to rows where Set is 'Z' and 'red' otherwise.

Solution with Numpy Select:

In cases where there are more than two conditions, np.select can be employed. Let's say color should meet the following criteria:

  • 'yellow' when Set is 'Z' and Type is 'A'
  • 'blue' when Set is 'Z' and Type is 'B'
  • 'purple' when Type is 'B'
  • 'black' otherwise

In this scenario, the code would be:

1

2

3

4

5

6

conditions = [

    (df['Set'] == 'Z') & (df['Type'] == 'A'),

    (df['Set'] == 'Z') & (df['Type'] == 'B'),

    (df['Type'] == 'B')]

choices = ['yellow', 'blue', 'purple']

df['color'] = np.select(conditions, choices, default='black')

Copy after login

This solution allows for flexible and granular condition-based value assignment for the new column.

The above is the detailed content of How to Create a New Column with Condition-Based Values in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template