Pandas groupby to to_csv

前端 未结 5 547
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 03:42

Want to output a Pandas groupby dataframe to CSV. Tried various StackOverflow solutions but they have not worked.

Python 3.6.1, Pandas 0.20.1

groupby result

5条回答
  •  北海茫月
    2020-12-10 04:05

    Try doing this:

    week_grouped = df.groupby('week')
    week_grouped.sum().reset_index().to_csv('week_grouped.csv')
    

    That'll write the entire dataframe to the file. If you only want those two columns then,

    week_grouped = df.groupby('week')
    week_grouped.sum().reset_index()[['week', 'count']].to_csv('week_grouped.csv')
    

    Here's a line by line explanation of the original code:

    # This creates a "groupby" object (not a dataframe object) 
    # and you store it in the week_grouped variable.
    week_grouped = df.groupby('week')
    
    # This instructs pandas to sum up all the numeric type columns in each 
    # group. This returns a dataframe where each row is the sum of the 
    # group's numeric columns. You're not storing this dataframe in your 
    # example.
    week_grouped.sum() 
    
    # Here you're calling the to_csv method on a groupby object... but
    # that object type doesn't have that method. Dataframes have that method. 
    # So we should store the previous line's result (a dataframe) into a variable 
    # and then call its to_csv method.
    week_grouped.to_csv('week_grouped.csv')
    
    # Like this:
    summed_weeks = week_grouped.sum()
    summed_weeks.to_csv('...')
    
    # Or with less typing simply
    week_grouped.sum().to_csv('...')
    

提交回复
热议问题