Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

python - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...