DF

2017-12-15 6 views
1

にグループ化値のランク1とランク2は、次のPythonのデータフレームを考慮して下さい:DF

>>> import pandas 
>>> df1 = pandas.DataFrame({"dish"  : ["fish", "chicken", "fish", "chicken", "chicken", "veg","veg"], 
...       "location" : ["central", "central", "north", "north", "south", "central", "north"], 
...       "sales" : [1,3,5,2,4,2,2]}) 
>>> total_sales = df1.groupby(by="dish").sum().reset_index().set_index(["dish"]) 
>>> df1["proportion_sales"] = df1.apply((lambda row: row["sales"]/total_sales.loc[row["dish"]]), axis=1) 
>>> df1 
     dish location sales proportion_sales 
0  fish central  1   0.166667 
1 chicken central  3   0.333333 
2  fish north  5   0.833333 
3 chicken north  2   0.222222 
4 chicken south  4   0.444444 
5  veg central  2   0.500000 
6  veg north  2   0.500000 

を私が1位にランクし、各location 2の皿にランクを知りたいです。例えば、centralで、chickenが1位にランクされ、fishはどのように私はそうのようになりdish_rank_in_location DFを更新します3.

位にランクされて?これは私が持っているものです。

 dish location sales proportion_sales rank 
0  fish central  1   0.166667  1 
1 chicken central  3   0.333333  1 
2  fish north  5   0.833333  1 
3 chicken north  2   0.222222  1 
4 chicken south  4   0.444444  1 
5  veg central  2   0.500000  1 
6  veg north  2   0.500000  1 

予想される出力:

 dish location sales proportion_sales dish_rank_in_location 
0  fish central  1   0.166667  3 
1 chicken central  3   0.333333  2 
2  fish north  5   0.833333  1 
3 chicken north  2   0.222222  3 
4 chicken south  4   0.444444  1 
5  veg central  2   0.500000  1 
6  veg north  2   0.500000  2 
+0

予想される出力を確認しますか?すべてがランク1です。 –

+0

はいランク1はランク2,3に更新する必要があります。この質問の問題は – bryansis2010

+0

です。 'df1.groupby(['location'])はどうでしょうか?proportion_sales.rank(method = 'dense')'? –

答えて

2

ここascending=Falsegroupby + rankを使用してください。

df1['dish_rank_in_location'].astype(int) 

0 3 
1 2 
2 1 
3 3 
4 1 
5 1 
6 2 
Name: dish_rank_in_location, dtype: int64 

が戻って結果を割り当てる -

df1['dish_rank_in_location'] = df1.groupby('location')\ 
       .proportion_sales.rank(method='dense', ascending=False) 

df1 

     dish location sales proportion_sales dish_rank_in_location 
0  fish central  1   0.166667     3.0 
1 chicken central  3   0.333333     2.0 
2  fish north  5   0.833333     1.0 
3 chicken north  2   0.222222     3.0 
4 chicken south  4   0.444444     1.0 
5  veg central  2   0.500000     1.0 
6  veg north  2   0.500000     2.0 

あなたは整数としてのランクが必要な場合は、常にキャストを行うことができます。