【问题标题】:Getting pandas dataframe rank answer different than SQL rank获得与 SQL 等级不同的熊猫数据框等级答案
【发布时间】:2020-11-10 03:00:34
【问题描述】:

我在 SQL 中学习 rank 函数,发现它使用的排序方式与 pandas 方法不同。如何得到相同的答案?

问题链接:https://www.windowfunctions.com/questions/ranking/1

SQL 代码

select rank() over (order by weight desc) as ranking, weight, name from cats order by ranking, name

我的熊猫代码

df[['weight','name']].assign(ranking=df['weight'].rank(method='dense',ascending=False)).sort_values('weight',ascending=False)

# I am getting a different answer than SQL
# How to get the same answer?

数据

df = pd.DataFrame({'name': ['Molly', 'Ashes', 'Felix', 'Smudge', 'Tigger', 'Alfie', 'Oscar', 'Millie', 'Misty', 'Puss', 'Smokey', 'Charlie'],
          'breed': ['Persian', 'Persian', 'Persian', 'British Shorthair', 'British Shorthair', 'Siamese', 'Siamese', 'Maine Coon', 'Maine Coon', 'Maine Coon', 'Maine Coon', 'British Shorthair'],
          'weight': [4.2, 4.5, 5.0, 4.9, 3.8, 5.5, 6.1, 5.4, 5.7, 5.1, 6.1, 4.8],
          'color': ['Black', 'Black', 'Tortoiseshell', 'Black', 'Tortoiseshell', 'Brown', 'Black', 'Tortoiseshell', 'Brown', 'Tortoiseshell', 'Brown', 'Black'],
          'age': [1, 5, 2, 4, 2, 5, 1, 5, 2, 2, 4, 4]})

我的输出

    weight  name    ranking
6   6.1 Oscar   1.0
10  6.1 Smokey  1.0
8   5.7 Misty   2.0 # this should be 3 and so on
5   5.5 Alfie   3.0
7   5.4 Millie  4.0
9   5.1 Puss    5.0
2   5.0 Felix   6.0
3   4.9 Smudge  7.0
11  4.8 Charlie 8.0
1   4.5 Ashes   9.0
0   4.2 Molly   10.0
4   3.8 Tigger  11.0

【问题讨论】:

标签: python sql pandas


【解决方案1】:

按照 cmets 的建议,我们可以使用这种方法在 SQL 和 pandas 中得到相同的答案:

df[['weight','name']].assign(ranking=df['weight'].rank(method='min',ascending=False)).sort_values('weight',ascending=False)

【讨论】:

    猜你喜欢
    • 2013-09-22
    • 2017-04-08
    • 1970-01-01
    • 2023-03-21
    • 2022-01-13
    • 2016-08-20
    • 2021-06-27
    • 2017-10-05
    相关资源
    最近更新 更多