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)
JavaScript
x
18
18
1
df = pd.DataFrame({
2
"products": ["Google", "Youtube", "Fitbit", "Nest", "Waze", "Meta", "Facebook", "Instagram", "Whatsapp"]
3
})
4
5
df
6
7
products
8
0 Google
9
1 Youtube
10
2 Fitbit
11
3 Nest
12
4 Waze
13
5 Meta
14
6 Facebook
15
7 Instagram
16
8 Whatsapp
17
18
Using pandas I would like the dataframe to be like this
Thank You
Advertisement
Answer
JavaScript
1
24
24
1
import numpy as np
2
import pandas as pd
3
4
5
companies = ["Google", "Meta"]
6
df = df.assign(
7
companies=np.where(df["products"].isin(companies), df["products"], "")
8
).set_index("companies")
9
10
df["products"] = df["products"].replace(companies, "")
11
print(df)
12
13
products
14
companies
15
Google
16
Youtube
17
Fitbit
18
Nest
19
Waze
20
Meta
21
Facebook
22
Instagram
23
Whatsapp
24