首页 > 解决方案 > 重命名数据帧索引中的值,然后 sort_index() 对重命名前的值抛出错误

问题描述

下面的代码从一些数据透视表数据生成一个图表。将索引中的值“<-24”重命名为“less”后的数据透视表数据如下图所示: 数据透视表数据

并非所有代码都包含在...

import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
import openpyxl
from datetime import datetime, timedelta
from openpyxl import load_workbook

...

# Creating the pivot table for a count of ship_id per hours_diff_last_ais_and_last_processed_grouped
HoursDiffLastAisProcessPivotTable = pd.pivot_table(todays_df, index=["hours_diff_last_ais_and_last_processed_grouped"], values=['ship_id'], aggfunc='count', fill_value='')


HoursDiffLastAisProcessPivotTable = HoursDiffLastAisProcessPivotTable[HoursDiffLastAisProcessPivotTable.index != 'nan']
HoursDiffLastAisProcessPivotTable.rename(index={'<-24': 'less'}, inplace=True)


# Set the sheet name and then use the function to output data into excel
hours_diff_sheet_name = 'Hours diff last AIS and Proces'
output_data_to_excel(today_hours_diff_data_file, hours_diff_sheet_name, HoursDiffLastAisProcessPivotTable)


# Creating a bar chart for the data in the pivot table
HoursDiffLastAisProcessGraph = HoursDiffLastAisProcessPivotTable.plot.bar(width=0.5)
plt.legend([todays_date], bbox_to_anchor=(0.5, -0.2), loc='center', borderaxespad=0., fontsize='x-small')
plt.xlabel('Hours')
plt.ylabel('Number of Ships')
plt.title('Hours diff between last AIS and last process Live or Launched')
plt.style.use('ggplot')
plt.rcParams.update({'axes.spines.top': False, 'axes.spines.right': False})
graph_path_file = new_last_processed_dir_name + '/Hours diff last AIS and Process Graph.png'
plt.savefig(graph_path_file, bbox_inches='tight')

这会生成一个如下所示的图表: 示例图表

但是,我想沿 x 轴从左到右对数据从最大到最小进行排序,在 x 轴的最右侧有 '<-24' 组。HoursDiffLastAisProcessPivotTable.sort_index(ascending=False, inplace=True)在使用 .rename() 之后,我尝试使用以下代码执行此操作

有没有办法让我从最大到最小对数据进行排序,其中组 '<-24' 被计为最小?(所以它显示在 x 轴的最右侧)

我目前收到以下错误:

  File "C:/Users/Michael Callum/MyPythonScripts/PivotTable1.py", line 71, in <module>
    HoursDiffLastAisProcessPivotTable.sort_index(ascending=False, inplace=True)
  File "C:\Users\Michael Callum\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\frame.py", line 5452, in sort_index
    indexer = nargsort(
  File "C:\Users\Michael Callum\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\sorting.py", line 308, in nargsort
    indexer = non_nan_idx[non_nans.argsort(kind=kind)]
TypeError: '<' not supported between instances of 'int' and 'str'

标签: pythonpandasdataframe

解决方案


问题是您不能混合使用字符串和整数进行排序。您可以将字符串值更改为低 int 以进行排序,然后将其更改回作为解决方法。

一种方法可以通过(有点难看但功能性)双重重命名来完成,但请注意,您必须将其分配给一个新变量,因为使用inplace=True会破坏方法链接,因为在适当的位置执行任何操作都会导致方法return None

hourdiffpivot=HoursDiffLastAisProcessPivotTable.rename({'less':-999}).sort_index(ascending=False).rename({-999:'less'})

然后您可以将变量名称重新分配给新创建的对象

HoursDiffLastAisProcessPivotTable=hourdiffpivot


推荐阅读