Pandas groupby to to_csv

前端 未结 5 562
隐瞒了意图╮
隐瞒了意图╮ 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:08

    Group By returns key, value pairs where key is the identifier of the group and the value is the group itself, i.e. a subset of an original df that matched the key.

    In your example week_grouped = df.groupby('week') is set of groups (pandas.core.groupby.DataFrameGroupBy object) which you can explore in detail as follows:

    for k, gr in week_grouped:
        # do your stuff instead of print
        print(k)
        print(type(gr)) # This will output 
        print(gr)
        # You can save each 'gr' in a csv as follows
        gr.to_csv('{}.csv'.format(k))
    

    Or alternatively you can compute aggregation function on your grouped object

    result = week_grouped.sum()
    # This will be already one row per key and its aggregation result
    result.to_csv('result.csv') 
    

    In your example you need to assign the function result to some variable as by default pandas objects are immutable.

    some_variable = week_grouped.sum() 
    some_variable.to_csv('week_grouped.csv') # This will work
    

    basically result.csv and week_grouped.csv are meant to be same

提交回复
热议问题