Home > Software design >  Pandas Set Index Based On Column Value
Pandas Set Index Based On Column Value

Time:10-10

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

enter image description here

Using pandas I would like the dataframe to be like this

enter image description here

Thank You

CodePudding user response:

Using pd.assign and np.where

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
  • Related