Get group id back into pandas dataframe

后端 未结 3 1123
别那么骄傲
别那么骄傲 2020-12-04 18:26

For dataframe

In [2]: df = pd.DataFrame({\'Name\': [\'foo\', \'bar\'] * 3,
   ...:                    \'Rank\': np.random.randint(0,3,6),
   ...:                     


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 19:06

    The correct solution is to use grouper.label_info:

    df["GroupId"] = df.groupby(["Name", "Rank"]).grouper.label_info
    

    It automatically associates each row in the df dataframe to the corresponding group label.

提交回复
热议问题