Converting a Pandas GroupBy output from Series to DataFrame

后端 未结 9 686
广开言路
广开言路 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:47

    The key is to use the reset_index() method.

    Use:

    import pandas
    
    df1 = pandas.DataFrame( { 
        "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , 
        "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } )
    
    g1 = df1.groupby( [ "Name", "City"] ).count().reset_index()
    

    Now you have your new dataframe in g1:

提交回复
热议问题