I’m new to pandas, I have a Dataframe read from excel file, like this screenshot below where Products
is the header and Google
and Meta
is the group (index)
df = pd.DataFrame({ "products": ["Google", "Youtube", "Fitbit", "Nest", "Waze", "Meta", "Facebook", "Instagram", "Whatsapp"] }) df products 0 Google 1 Youtube 2 Fitbit 3 Nest 4 Waze 5 Meta 6 Facebook 7 Instagram 8 Whatsapp
Using pandas I would like the dataframe to be like this
Thank You
Advertisement
Answer
import numpy as np import pandas as pd companies = ["Google", "Meta"] df = df.assign( companies=np.where(df["products"].isin(companies), df["products"], "") ).set_index("companies") df["products"] = df["products"].replace(companies, "") print(df) products companies Google Youtube Fitbit Nest Waze Meta Facebook Instagram Whatsapp