我有一个dataframe,我尝试从Groupby导出到Excel的结果由自定义排序值一个,两个或更多列:
- id排序方式
['bv','cl','an']
- 颜色按
['blue','red','orange','green']
排序
import pandas as pd
data = {'color': ['green', 'red', ' orange', 'red','blue',' orange', 'red','blue', 'red', ' orange', 'red','red','green'],
'Name': ['Tom', 'nick', 'krish', 'jack','bob','Tom', 'nick', 'krish', 'nick', 'krish', 'jack','nick','Tom'],
'form': [ 'a', 'b', 'c', 'd','e','b', 'c', 'd','d','e','b', 'c', 'b'],
'id': [ 'an', 'bv', 'cl', 'cl','an','bv', 'an', 'cl','cl', 'an','bv','bv','an'],
}
df = pd.DataFrame(data)
print(df)
df_1 = df.groupby(['color','Name','id'])['form'].agg('count')
print(df_1)
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df_1.to_excel(writer, sheet_name='Sheet1')
writer.save()
print(' I try the df to excel have custom sort values in columns')
print('id sort by [bv,cl,an]')
print('color sort by [blue,red,orange,green]')
print('how can make it?')
1条答案
按热度按时间b1zrtrql1#
你可以先使用Categorical Data,然后使用
sort_index
:输出: