国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

pandas 透視表中文字段排序方法

2020-01-04 14:03:27
字體:
來源:轉載
供稿:網友

前幾天有一個需求,透視表中的年級這一列要按照一年級,二年級這樣的序列進行排序,但是用過透視表的人都知道,透視表對中文的排序不是太理想,放棄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_colscols_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 透視表中文字段排序方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 静乐县| 崇礼县| 洛宁县| 宣化县| 呼伦贝尔市| 鹰潭市| 通山县| 辛集市| 孙吴县| 垦利县| 广州市| 奉节县| 嘉义市| 尖扎县| 黄龙县| 桃园市| 永丰县| 砚山县| 兴文县| 进贤县| 新巴尔虎右旗| 绿春县| 三都| 葫芦岛市| 修文县| 永新县| 罗山县| 湟源县| 玉屏| 望谟县| 宁乡县| 闸北区| 房产| 孝感市| 宁化县| 台湾省| 台前县| 瓮安县| 福贡县| 股票| 二连浩特市|