Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PANDAS split dataframe to multiple by unique values rows

I have a DataFrame in Pandas

      PRICE   Name     PER   CATEGORY   STORENAME
0      9.99    MF      gram  Indica     Store1
1      9.99    HY      gram  Herb       Store2
2      9.99    FF      gram  Herb       Store2

What I want to do is split these into multiple data frames to have unique names, then in those split to category.

Current code:

names = df['STORENAME'].unique().tolist()   #find unique values
store1 = df[df['STORENAME']==names[0]]        
store2 = df[df['STORENAME']==names[1]]

This code works perfectly but I am wondering if there is a Pythonic way since the number of stores may change.

This is needed to plot the difference in prices in categories in stores.

Thanks!

like image 757
Darshan Jadav Avatar asked Dec 12 '17 09:12

Darshan Jadav


People also ask

How do I extract unique rows in pandas?

And you can use the following syntax to select unique rows across specific columns in a pandas DataFrame: df = df. drop_duplicates(subset=['col1', 'col2', ...])

How do I group unique values in pandas?

To count unique values per groups in Python Pandas, we can use df. groupby('column_name').


1 Answers

I think you can create dictionary of DataFrames:

dfs = dict(tuple(df.groupby('STORENAME')))

And then select by STORENAME:

store1 = dfs['Store1']
store2 = dfs['Store2']

print (store1)
   PRICE Name   PER CATEGORY STORENAME
0   9.99   MF  gram   Indica    Store1

print (store2)
   PRICE Name   PER CATEGORY STORENAME
1   9.99   HY  gram     Herb    Store2
2   9.99   FF  gram     Herb    Store2
like image 82
jezrael Avatar answered Oct 15 '22 08:10

jezrael