忽略某些值对 pandas DataFrame 进行排序

有一个值接近 1 和接近 0 的 pandas DataFrame:


df = pd.DataFrame({

'colA': (0.97, 0.88, 0.03, 0.02),

'colB': (0.01, 0.03, 0.87, 0.99),

})

根据值排序给出(排序colB显然没有效果):


df.sort_values(['colA','colB'], ascending=False)

>>    colA  colB

>> 0  0.97  0.01

>> 1  0.88  0.03

>> 2  0.03  0.87

>> 3  0.02  0.99

但是,我只想根据较大的值进行排序,比如> 0.5. 这将忽略较小的值colA并切换到以colB进行进一步排序。


排序后的 DataFrame 看起来像这样(row 2并且3已切换):


df.some_function(['colA','colB'], ascending=False, condition=i>0.5)

>>    colA  colB

>> 0  0.97  0.01

>> 1  0.88  0.03

>> 2  0.02  0.99

>> 3  0.03  0.87

非常感谢你的帮助!


富国沪深
浏览 179回答 3
3回答

冉冉说

想法是将不匹配的值替换为缺失值然后排序,最后按新索引更改顺序:idx = (df[['colA','colB']].where(df[['colA','colB']] > 0.5)           .sort_values(['colA','colB'], ascending=False).index)df1 = df.loc[idx]print (df1)   colA  colB0  0.97  0.011  0.88  0.033  0.02  0.992  0.03  0.87细节:print (df[['colA','colB']].where(df[['colA','colB']] > 0.5))   colA  colB0  0.97   NaN1  0.88   NaN2   NaN  0.873   NaN  0.99print (df[['colA','colB']].where(df[['colA','colB']] > 0.5)                          .sort_values(['colA','colB'], ascending=False))   colA  colB0  0.97   NaN1  0.88   NaN3   NaN  0.992   NaN  0.87

回首忆惘然

构建一个与“a”相同但忽略较小值的新列,并使用此新值和“b”进行排序:df.assign(simplified_a = np.where(df.colA<0.5, 0, df.colA))\&nbsp; .sort_values(["simplified_a", "colB"], ascending=False).drop("simplified_a", axis=1)结果:&nbsp; &nbsp;colA&nbsp; colB0&nbsp; 0.97&nbsp; 0.011&nbsp; 0.88&nbsp; 0.033&nbsp; 0.02&nbsp; 0.992&nbsp; 0.03&nbsp; 0.87

海绵宝宝撒

根据条件过滤数据场,然后排序,然后追加df1 = df.where(df['colA'] > 0.5).sort_values('colA')df2 = df.where(df['colA'] <= 0.5).sort_values('colB')final_frame = df1.append(df2).dropna()&nbsp; &nbsp;colA&nbsp; colB0&nbsp; 0.87&nbsp; 0.011&nbsp; 0.88&nbsp; 0.032&nbsp; 0.03&nbsp; 0.873&nbsp; 0.02&nbsp; 0.99
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python