Converting a Pandas GroupBy output from Series to DataFrame

后端 未结 9 744
广开言路
广开言路 2020-11-22 09:58

I\'m starting with input data like this

df1 = pandas.DataFrame( { 
    \"Name\" : [\"Alice\", \"Bob\", \"Mallory\", \"Mallory\", \"Bob\" , \"Mallory\"] , 
           


        
9条回答
  •  醉话见心
    2020-11-22 10:51

    Simply, this should do the task:

    import pandas as pd
    
    grouped_df = df1.groupby( [ "Name", "City"] )
    
    pd.DataFrame(grouped_df.size().reset_index(name = "Group_Count"))
    

    Here, grouped_df.size() pulls up the unique groupby count, and reset_index() method resets the name of the column you want it to be. Finally, the pandas Dataframe() function is called upon to create a DataFrame object.

提交回复
热议问题