how to filter data based on more than 1 unique category in python pandas

Viewed 90

I have a dataset given below:

price    category    company          time
10          A         "Walmart"       01/01/2020
20          A         "Walmart"       02/01/2020
30          A         "Macy"          01/01/2020
40          A         "Ross"          01/01/2020
50          B         "Ross"          02/01/2020
60          A         "Starbucks"     01/01/2020
70          B         "Starbucks"     02/01/2020

I am trying to filter this data based on the number of categories which has more than 1 unique categories. Filtered data that has more than 1 unique categories are given below:

price    category    company          time
40          A         "Ross"          01/01/2020
50          B         "Ross"          02/01/2020
60          A         "Starbucks"     01/01/2020
70          B         "Starbucks"     02/01/2020

Is there any way to do this efficiently in pandas python? Thanks.

2 Answers

Can use nunique and transform

df[df.groupby('company')['category'].transform('nunique') > 1]

You can try something like that :

  • CODE:
companies=list(df['company'].unique())

df_final=[]
for i in range(len(companies)):
    
    temp = df[df['company']==companies[i]]
    
    if temp.category.nunique()>=2 :
        
        df_final.append(temp)
        
    
data_final=pd.concat(df_final,ignore_index=True)
data_final
  • OUTPUT:
   price    category        company            time
0   40         A             Ross          01/01/2020
1   50         B             Ross          02/01/2020
2   60         A             Starbucks     01/01/2020
3   70         B             Starbucks     02/01/2020

I hope to be helpful!!

Related