重命名了数据帧索引中的值,然后sort_index()在重命名前的值上抛出错误



下面的代码从一些透视表数据生成一个图。其中数据透视表数据在我重命名了值'&lt-"less"的索引中的24'如下图所示:数据透视表数据

并不是所有的代码都包含在。。。

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轴从左到右从最大到最小对数据进行排序,其中'&lt-24’组在x轴的最右侧。我尝试使用以下代码来完成此操作我使用.rename((后的HoursDiffLastAisProcessPivotTable.sort_index(ascending=False, inplace=True)

有没有一种方法可以让我把数据从大到小排序,其中组'&lt-24英寸算最小?(所以它显示在x轴的最右边(

我目前得到以下错误:

File "C:/Users/Michael Callum/MyPythonScripts/PivotTable1.py", line 71, in <module>
HoursDiffLastAisProcessPivotTable.sort_index(ascending=False, inplace=True)
File "C:UsersMichael CallumAppDataLocalProgramsPythonPython38-32libsite-packagespandascoreframe.py", line 5452, in sort_index
indexer = nargsort(
File "C:UsersMichael CallumAppDataLocalProgramsPythonPython38-32libsite-packagespandascoresorting.py", line 308, in nargsort
indexer = non_nan_idx[non_nans.argsort(kind=kind)]
TypeError: '<' not supported between instances of 'int' and 'str'

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

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

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

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

HoursDiffLastAisProcessPivotTable=hourdiffpivot

最新更新