PANDAS 按唯一值行将数据帧拆分为多个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47769453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:53:29  来源:igfitidea点击:

PANDAS split dataframe to multiple by unique values rows

pythonpandasdataframe

提问by Darshan Jadav

I have a DataFrame in Pandas

我在 Pandas 中有一个 DataFrame

      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.

这段代码运行良好,但我想知道是否有 Pythonic 方式,因为商店的数量可能会改变。

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

这是绘制商店中类别价格差异所必需的。

Thanks!

谢谢!

回答by jezrael

I think you can create dictionary of DataFrames:

我认为你可以创建dictionary of DataFrames

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

And then select by STORENAME:

然后选择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