Home > Backend Development > Python Tutorial > How Can I Create New Columns with Conditional Values in DataFrames Using NumPy?

How Can I Create New Columns with Conditional Values in DataFrames Using NumPy?

Susan Sarandon
Release: 2024-12-31 01:10:13
Original
338 people have browsed it

How Can I Create New Columns with Conditional Values in DataFrames Using NumPy?

Creating a New Column with Conditional Values

When analyzing data, it may be necessary to create new columns where the values are selected based on existing columns. This allows you to categorize or transform data for further analysis or visualization. Here are two approaches:

np.where for Two Choices:

If you need to choose between only two values based on an existing column, you can use the np.where function. For instance, to create a "color" column in a dataframe where "color='green'" if "Set=='Z'" and "color='red'" otherwise, you can use:

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

np.select for Multiple Conditions:

If you have more than two conditions to consider when selecting values, you can use the np.select function. For example, to create a "color" column based on multiple conditions:

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

By using np.where or np.select, you can easily create new columns with conditional values, providing flexibility in data manipulation and enabling deeper insights from your data.

The above is the detailed content of How Can I Create New Columns with Conditional Values in DataFrames Using NumPy?. 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