首页 > 解决方案 > 对 df 进行排序,但从排序中排除前 2 列

问题描述

我想对 df 进行排序,但我想从排序中排除前 2 列。

我能够在排除前 1 列的同时成功排序,但我想更新下面的代码以排除前 2 列。

from pandas import DataFrame
Cars = {'Dimensions': [0.48,0.44,0.4,0.6],
        'Price': [0.3,0.25,0.74,0.5],
        'Year': [0.41,0.38,0.64,0.65],
        'Range': [0.95,0.98,0.24,0.42],
        'Height': [0.75,0.88,0.84,0.95],
        }

df = DataFrame(Cars, columns= ['Dimensions', 'Price','Year', 'Range', 'Height'], 
               index=['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'])

s = df.iloc[0]
df = df.iloc[:, ((-s[1:]).argsort() + 1).reindex(df.columns, fill_value=0)]

我认为这会起作用,但事实并非如此

s = df.iloc[0:1]
df = df.iloc[:, ((-s[1:]).argsort() + 1).reindex(df.columns, fill_value=0)]

错误:

AttributeError: 'DataFrame' object has no attribute 'argsort'

期望输出:

                Dimensions  Price  Range  Height  Year  
Honda Civic           0.48   0.30   0.95    0.75  0.41  
Toyota Corolla        0.44   0.25   0.98    0.88  0.38 
Ford Focus            0.40   0.74   0.24    0.84  0.64  
Audi A4               0.60   0.50   0.42    0.95  0.65 

标签: pandassorting

解决方案


问题是Series索引返回一行DataFrame,并且因为argsort已实现但仅用于Series引发错误:

s = df.iloc[0:1]
print (s)
             Dimensions  Price  Year  Range  Height
Honda Civic        0.48    0.3  0.41   0.95    0.75

对于排除前 2 列Series,为填充的前 2 列添加帮助器,0,1s[2:]为省略前 2 个索引值添加:

s = df.iloc[0]

new = pd.Series([0,1], index=df.columns[:2])
df = df.iloc[:, new.append( ((-s[2:]).argsort() + 2))]
print (df)
                Dimensions  Price  Range  Height  Year
Honda Civic           0.48   0.30   0.95    0.75  0.41
Toyota Corolla        0.44   0.25   0.98    0.88  0.38
Ford Focus            0.40   0.74   0.24    0.84  0.64
Audi A4               0.60   0.50   0.42    0.95  0.65

推荐阅读