在 pandas 中,如何按照自定义规则对列按值进行分组排序。

huangapple go评论135阅读模式
英文:

how in pandas groupby custom sort columns by value

问题

I have a dataframe and I try the results from Groupby export to excel by custom sort values one, two or more columns:

  • id sorted by ['bv', 'cl', 'an']
  • color sorted by ['blue', 'red', 'orange', 'green']
  1. import pandas as pd
  2. data = {'color': ['green', 'red', ' orange', 'red','blue',' orange', 'red','blue', 'red', ' orange', 'red','red','green'],
  3. 'Name': ['Tom', 'nick', 'krish', 'jack','bob','Tom', 'nick', 'krish', 'nick', 'krish', 'jack','nick','Tom'],
  4. 'form': [ 'a', 'b', 'c', 'd','e','b', 'c', 'd','d','e','b', 'c', 'b'],
  5. 'id': [ 'an', 'bv', 'cl', 'cl','an','bv', 'an', 'cl','cl','an','bv','bv','an'],
  6. }
  7. df = pd.DataFrame(data)
  8. print(df)
  9. df_1 = df.groupby(['color','Name','id'])['form'].agg('count')
  10. print(df_1)
  11. writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
  12. df_1.to_excel(writer, sheet_name='Sheet1')
  13. writer.save()
  14. print('I try the df to excel have custom sort values in columns')
  15. print('id sort by [bv,cl,an]')
  16. print('color sort by [blue,red,orange,green]')
  17. print('how can make it?')

(Note: I have provided the code without translation as requested.)

英文:

I have a dataframe and i try the results from Groupby export to excel by custom sort values one , two or more columns :

  • id sorted by ['bv','cl','an']
  • color sorted by ['blue','red','orange','green']
  1. import pandas as pd
  2. data = {'color': ['green', 'red', ' orange', 'red','blue',' orange', 'red','blue', 'red', ' orange', 'red','red','green'],
  3. 'Name': ['Tom', 'nick', 'krish', 'jack','bob','Tom', 'nick', 'krish', 'nick', 'krish', 'jack','nick','Tom'],
  4. 'form': [ 'a', 'b', 'c', 'd','e','b', 'c', 'd','d','e','b', 'c', 'b'],
  5. 'id': [ 'an', 'bv', 'cl', 'cl','an','bv', 'an', 'cl','cl', 'an','bv','bv','an'],
  6. }
  7. df = pd.DataFrame(data)
  8. print(df)
  9. df_1 = df.groupby(['color','Name','id'])['form'].agg('count')
  10. print(df_1)
  11. writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
  12. df_1.to_excel(writer, sheet_name='Sheet1')
  13. writer.save()
  14. print(' I try the df to excel have custom sort values in columns')
  15. print('id sort by [bv,cl,an]')
  16. print('color sort by [blue,red,orange,green]')
  17. print('how can make it?')

答案1

得分: 1

You can use 分类数据 然后 sort_index

  1. ids = pd.CategoricalDtype(["bv", "cl", "an"], ordered=True)
  2. colors = pd.CategoricalDtype(["blue", "red", "orange", "green"], ordered=True)
  3. # 如有需要,添加更多类别
  4. out = (
  5. df.astype({"id": ids, "color": colors})
  6. .groupby(["color", "Name", "id"], observed=True)["form"].agg("count")
  7. .sort_index(level=[0, 2]) # 如有需要,添加更多级别
  8. )
  9. with pd.ExcelWriter("test.xlsx", engine="xlsxwriter") as writer:
  10. out.to_excel(writer, sheet_name="Sheet1")
  11. # 如有需要,添加自定义样式/格式化

输出:

  1. print(out)
  2. color Name id
  3. blue krish cl 1
  4. bob an 1
  5. red jack bv 1
  6. nick bv 2
  7. jack cl 1
  8. nick cl 1
  9. an 1
  10. orange Tom bv 1
  11. krish cl 1
  12. an 1
  13. green Tom an 2
  14. Name: form, dtype: int64
英文:

You can use Categorical Data then sort_index :

  1. ids = pd.CategoricalDtype(["bv", "cl", "an"], ordered=True)
  2. colors = pd.CategoricalDtype(["blue", "red", "orange", "green"], ordered=True)
  3. #add here more categories if needed
  4. out = (
  5. df.astype({"id": ids, "color": colors})
  6. .groupby(["color", "Name", "id"], observed=True)["form"].agg("count")
  7. .sort_index(level=[0, 2]) #in case, add here more levels
  8. )
  9. with pd.ExcelWriter("test.xlsx", engine="xlsxwriter") as writer:
  10. out.to_excel(writer, sheet_name="Sheet1")
  11. # add here a custom styling/formatting if needed

Output :

  1. print(out)
  2. color Name id
  3. blue krish cl 1
  4. bob an 1
  5. red jack bv 1
  6. nick bv 2
  7. jack cl 1
  8. nick cl 1
  9. an 1
  10. orange Tom bv 1
  11. krish cl 1
  12. an 1
  13. green Tom an 2
  14. Name: form, dtype: int64

huangapple
  • 本文由 发表于 2023年6月18日 19:53:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76500410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定