Template request | Bug report | Generate Data Product
Tags: #pandas #snippet #datenrichment #operations
Author: Florent Ravenel
Description: This notebook demonstrates the practical application of DataFrame.loc
for implementing conditions, enabling users to seamlessly enrich a DataFrame by generating new columns based on conditions derived from existing ones. Its versatility makes it an invaluable tool for DataFrame manipulation.
References:
import pandas as pd
new_column
: column label to be created
new_column = "ranking"
# create DataFrame
df = pd.DataFrame(
{
"team": ["A", "A", "A", "B", "B", "B"],
"points": [11, 7, 8, 10, 13, 13],
"assists": [5, 7, 7, 9, 12, 9],
"rebounds": [11, 8, 10, 6, 6, 5],
}
)
df
df.loc[:, new_column] = "C" #apply condition on all rows with ':'
df.loc[(df["points"] >= 10) & (df["assists"] >= 5) & (df["rebounds"] >= 5), new_column] = "B"
df.loc[(df["points"] >= 10) & (df["assists"] >= 5) & (df["rebounds"] >= 10), new_column] = "A"
df.loc[(df["points"] >= 10) & (df["assists"] >= 10) & (df["rebounds"] >= 5), new_column] = "A"
df