根据列值对输入值进行排名

需要帮助根据输入值分配排名/变量以及百分位数列值的位置示例:


If input value = Min column value --> Rank 1

input value between Min column value and P25 column value --> Rank 2

input value between P75 column value and Max column value --> Rank 5

input value = Max column value --> Rank 6

这是示例数据:


    date | value | Min  | P25  | P50  | P75  | Max       | output

    ---------------------------------------------------

    1-Sep| 45    | 12.0 | 28.2 | 48.9 | 85.4 | 98.0      | 3

    2-Sep| 63    | 12.0 | 28.2 | 48.9 | 85.4 | 98.0      | 4

    3-Sep| 87    | 12.0 | 28.2 | 48.9 | 85.4 | 98.0      | 5

    4-Sep| 12    | 12.0 | 28.1 | 48.9 | 85.2 | 98.0      | 1

    5-Sep| 89    | 14.2 | 28.8 | 48.9 | 85.8 | 98.0      | 5

    6-Sep| 98    | 14.2 | 28.8 | 48.9 | 85.8 | 98.0      | 6

    7-Sep| 41    | 14.2 | 28.8 | 48.9 | 85.6 | 97.9      | 3

    8-Sep| 22    | 14.2 | 28.8 | 48.9 | 85.6 | 97.9      | 2

排名字典(配置)是这样的:([Min:1, P25:2, P50:3, p75:4, Max:5, Max:6]如果有更好的表示方式可以更改)


我尝试过使用排序值(同时使用应用函数),但无法找出最小/最大条件。这个 pandas df 有 100k+ 行。


杨魅力
浏览 84回答 1
1回答

梵蒂冈之花

您可以使用np.select以下方法来执行此操作:cond1 = df['value'] <= df['Min']cond2 = df['value'] <= df['P25']cond3 = df['value'] <= df['P50']cond4 = df['value'] <= df['P75']cond5 = df['value'] < df['Max']df['rank'] = np.select([cond1, cond2, cond3, cond4, cond5], [1,2,3,4,5], 6)df输出:&nbsp; &nbsp; &nbsp; &nbsp; date&nbsp; value&nbsp; &nbsp;Min&nbsp; &nbsp;P25&nbsp; &nbsp;P50&nbsp; &nbsp;P75&nbsp; &nbsp;Max&nbsp; output&nbsp; rank1&nbsp; &nbsp; &nbsp; 1-Sep&nbsp; &nbsp;45.0&nbsp; 12.0&nbsp; 28.2&nbsp; 48.9&nbsp; 85.4&nbsp; 98.0&nbsp; &nbsp; &nbsp;3.0&nbsp; &nbsp; &nbsp;32&nbsp; &nbsp; &nbsp; 2-Sep&nbsp; &nbsp;63.0&nbsp; 12.0&nbsp; 28.2&nbsp; 48.9&nbsp; 85.4&nbsp; 98.0&nbsp; &nbsp; &nbsp;4.0&nbsp; &nbsp; &nbsp;43&nbsp; &nbsp; &nbsp; 3-Sep&nbsp; &nbsp;87.0&nbsp; 12.0&nbsp; 28.2&nbsp; 48.9&nbsp; 85.4&nbsp; 98.0&nbsp; &nbsp; &nbsp;5.0&nbsp; &nbsp; &nbsp;54&nbsp; &nbsp; &nbsp; 4-Sep&nbsp; &nbsp;12.0&nbsp; 12.0&nbsp; 28.1&nbsp; 48.9&nbsp; 85.2&nbsp; 98.0&nbsp; &nbsp; &nbsp;1.0&nbsp; &nbsp; &nbsp;15&nbsp; &nbsp; &nbsp; 5-Sep&nbsp; &nbsp;89.0&nbsp; 14.2&nbsp; 28.8&nbsp; 48.9&nbsp; 85.8&nbsp; 98.0&nbsp; &nbsp; &nbsp;5.0&nbsp; &nbsp; &nbsp;56&nbsp; &nbsp; &nbsp; 6-Sep&nbsp; &nbsp;98.0&nbsp; 14.2&nbsp; 28.8&nbsp; 48.9&nbsp; 85.8&nbsp; 98.0&nbsp; &nbsp; &nbsp;6.0&nbsp; &nbsp; &nbsp;67&nbsp; &nbsp; &nbsp; 7-Sep&nbsp; &nbsp;41.0&nbsp; 14.2&nbsp; 28.8&nbsp; 48.9&nbsp; 85.6&nbsp; 97.9&nbsp; &nbsp; &nbsp;3.0&nbsp; &nbsp; &nbsp;38&nbsp; &nbsp; &nbsp; 8-Sep&nbsp; &nbsp;22.0&nbsp; 14.2&nbsp; 28.8&nbsp; 48.9&nbsp; 85.6&nbsp; 97.9&nbsp; &nbsp; &nbsp;2.0&nbsp; &nbsp; &nbsp;2
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python