pandas透视表中文排序解决方案:映射法实现自定义顺序
针对pandas透视表对中文排序支持不佳的问题,本文介绍一种通过数字映射实现自定义排序的方法。核心思路是将需要特殊排序的中文列转换为对应的数字序列,生成透视表后,再将索引或列名中的数字替换回中文,从而获得符合预期顺序的透视表结果。
在处理数据透视表时,常遇到需要按特定逻辑(如“一年级”、“二年级”等)对中文字段进行排序的需求。然而,pandas默认的透视表排序机制对中文支持并不理想,直接调用内置排序方法往往无法达到预期效果。经过多次尝试,发现一种有效的替代方案:首先,将DataFrame中涉及特殊排序要求的列中的中文内容转换为对应的数字编码;接着,基于转换后的数据生成透视表;最后,在透视表生成完成后,将索引(index)或列名(columns)中的数字重新映射回原始的中文文本。通过这一系列操作,即可实现按自定义顺序排列的透视表输出。
def get_special_sort_data(self, groupby, columns):
# 获取需要特殊处理的字段的信息
special_sort_cols = None
cols_in_index_or_column = None # 判断特殊排序字段在index还是column中
if self.datasource.has_special_sort_cols:
# 获取表需要处理的特殊字段信息
special_sort_cols = self.datasource.get_sort_columns() # {"grade_name": {}}
if special_sort_cols:
i_intersection = list(set(groupby) & set(special_sort_cols.keys()))
c_intersection = list(set(columns) & set(special_sort_cols.keys()))
if i_intersection:
cols_in_index_or_column = ('index', i_intersection)
elif c_intersection:
cols_in_index_or_column = ('column', c_intersection)
return cols_in_index_or_column, special_sort_cols
cols_in_index_or_column, special_sort_cols = self.get_special_sort_data(groupby, columns) # special_sort_cols:{"grade_name": {"一年级": 1, "二年级":2, "三年级": 3 ....}}
if cols_in_index_or_column:
for col in cols_in_index_or_column[1]:
df[col] = df[col].replace(special_sort_cols.get(col)) # 替换df
# 获取透视表
if cols_in_index_or_column:
if cols_in_index_or_column[0] == 'index':
if len(groupby) == 1:
col_name = cols_in_index_or_column[1][0]
sort_info = special_sort_cols.get(col_name)
r_sort_info = {v:k for k, v in zip(sort_info.keys(), sort_info.values())}
index_1 = df.index.tolist()
index_1 = [r_sort_info.get(item) for item in index_1]
df.index = Index(index_1, name=df.index.name)
else:
for item in cols_in_index_or_column[1]:
ix = df.index.names.index(item)
index_1 = df.index.levels[ix].tolist()
sort_info = special_sort_cols.get(item)
r_sort_info = {v: k for k, v in zip(sort_info.keys(), sort_info.values())}
index_1 = [r_sort_info.get(item) for item in index_1]
df.index = df.index.set_levels(index_1, level=ix)
else:
for item in cols_in_index_or_column[1]:
ix = df.columns.names.index(item)
col_1 = df.columns.levels[ix].tolist()
sort_info = special_sort_cols.get(item)
r_sort_info = {v: k for k, v in zip(sort_info.keys(), sort_info.values())}
col_1 = [r_sort_info.get(item) for item in col_1]
df.columns = df.columns.set_levels(col_1, level=ix)
上述方法提供了pandas透视表中处理中文排序的一种可行思路,供各位开发者参考。希望此方案能帮助大家解决类似的数据展示问题,也欢迎继续支持本站获取更多技术分享。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













