简体   繁体   中英

How to display the column names on group by result in Python when writing into CSV file?

I have an input data like this,

ID days
1  02
1  24
2  12
3  10

Expected result in csv file should be

ID Avg. days
1  13
2  12
3  10

with my code, I am able to get only the mean value , not able to get ID. But I need it both.

ID = tempx.groupby('ID')['days'].mean()
ID.to_csv("file1.csv", sep=',',encoding='utf-8',index = False)

will anyone please help me how to get the columns as header with group by result?

Don't pass index=False

tempx.groupby('ID').days.mean().to_frame('Avg. days').to_csv(
    'file.csv', encoding='utf-8')

.groupby('ID') sets 'ID' to be the index. Either save your file like this:

ID = tempx.groupby('ID')['days'].mean()
ID.to_csv("file1.csv", sep=',',encoding='utf-8',index = True)

Or groupby with as_index = False

ID = tempx.groupby('ID', as_index = False)['days'].mean()
ID.to_csv("file1.csv", sep=',',encoding='utf-8',index = False)

I think you need reset_index with parameter name :

ID = tempx.groupby('ID')['days'].mean().reset_index(name='Avg. days')
print (ID)
   ID  Avg. days
0   1         13
1   2         12
2   3         10

ID.to_csv("file1.csv", sep=',',encoding='utf-8',index = False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM