pandas - 对 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
解决方案
问题是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,1
并s[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
推荐阅读
- reactjs - 如何使用 typescript 有条件地将 true 或 false 传递给 React 布尔道具?
- mongodb - 在 MongoDB 聚合查询中获取“[[Object]]”作为对象响应的嵌套数组
- audio - 试图用 OCTAVE 制作频谱
- javascript - 对 SVG 元素坐标应用变换以获得新坐标
- django - 未找到带有参数 '('chempion',)' 的 'post_detail' 的反向操作。尝试了 1 种模式:['(?P
- import - Azure DevOps Server 2020 迁移导入 (ProductionRun) 失败
- javascript - Jquery从字符串中删除和标记
- javascript - 数组过滤另一个数组
- java - 在数组的每个索引中计算“,”之前的字符,并返回最高的
- c - malloc():fwrite 上损坏的顶部大小