gpt4 book ai didi

python - 获取与 SQL rank 不同的 pandas dataframe rank answer

转载 作者:行者123 更新时间:2023-12-05 07:04:09 25 4
gpt4 key购买 nike

我在学习 SQL 中的排名函数,发现它使用的排名与 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

我的 Pandas 代码

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

最佳答案

正如评论中所建议的,我们可以使用这种方法在 SQL 和 pandas 中得到相同的答案:

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

关于python - 获取与 SQL rank 不同的 pandas dataframe rank answer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63002515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com