排序 - TypeError: 'int' 和 'str' 的实例之间不支持 '<',Python

Vin*_* TP 3 python sorting

我正在尝试对 excel 进行排序,但出现以下错误:

File "D:\Projects\Project1\venv\lib\site-packages\pandas\core\frame.py", line 4725, in sort_values
    na_position=na_position)
  File "D:\Projects\Project1\venv\lib\site-packages\pandas\core\sorting.py", line 273, in nargsort
    indexer = non_nan_idx[non_nans.argsort(kind=kind)]
TypeError: '<' not supported between instances of 'int' and 'str'
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下代码行,如何解决此问题。

excel_file = pd.ExcelFile('file1.xlsx')
    df = excel_file.parse('Sheet1')
    df = df.sort_values(by=['Name'], ascending=True)

    writer = ExcelWriter('File2.xlsx')
    df.to_excel(writer, 'Sheet1', index=False)
    writer.save()
Run Code Online (Sandbox Code Playgroud)

the*_*orm 6

听起来您的“名称”列具有混合数据类型 - 一些字符串和一些整数。您可以通过在进行排序之前将列转换为字符串类型来将整数视为字符串:

df['Name'] = df['Name'].astype(str)
df.sort_values(by='Name', ascending=True, inplace=True)
Run Code Online (Sandbox Code Playgroud)

也就是说,听起来像名为“Name”的列中不应该包含整数,因此我可能建议在继续使用此解决方案之前更仔细地检查您的数据。