Home > Backend Development > Python Tutorial > How to Create a New Column in Pandas Based on Conditional Logic Across Multiple Columns?

How to Create a New Column in Pandas Based on Conditional Logic Across Multiple Columns?

Barbara Streisand
Release: 2024-12-10 19:30:12
Original
226 people have browsed it

How to Create a New Column in Pandas Based on Conditional Logic Across Multiple Columns?

Create New Column Based on Conditional Criteria from Multiple Columns

To create a new column based on conditional criteria from multiple columns, apply your custom function to all rows in your DataFrame using the apply() method.

import pandas as pd

def label_race(row):
    if row['eri_hispanic'] == 1:
        return 'Hispanic'
    elif row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1:
        return 'Two Or More'
    elif row['eri_nat_amer'] == 1:
        return 'A/I AK Native'
    elif row['eri_asian'] == 1:
        return 'Asian'
    elif row['eri_afr_amer'] == 1:
        return 'Black/AA'
    elif row['eri_hawaiian'] == 1:
        return 'Haw/Pac Isl.'
    elif row['eri_white'] == 1:
        return 'White'
    else:
        return 'Other'

df['race_label'] = df.apply(label_race, axis=1)
Copy after login

The resulting DataFrame will contain the new column, race_label, with the corresponding race labels based on the criteria you specified.

The above is the detailed content of How to Create a New Column in Pandas Based on Conditional Logic Across Multiple Columns?. 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