python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > dataframe排序 pd.rank()

关于dataframe排序 pd.rank()

作者:羊羊猪

pandas.DataFrame.rank方法支持不同的排序方式,如按行或列、升序或降序等,主要参数包括axis控制按行或列排名,method定义相同值的处理方式,numeric_only指定是否仅对数字列排序,na_option设置NaN值的排序方法,ascending确定排序方向,pct决定是否以百分比形式展示排名

pandas.DataFrame.rank

pandas.DataFrame.rank 官方文档

DataFrame.rank(axis=0, method=‘average', numeric_only=NoDefault.no_default, na_option=‘keep', ascending=True, pct=False)

参数解释

Example:

df = pd.DataFrame(data={'Animal': ['cat', 'penguin', 'dog',
                                   'spider', 'snake'],
                        'Number_legs': [4, 2, 4, 8, np.nan]})

method: {‘average', ‘min', ‘max', ‘first', ‘dense'}, default ‘average'
df['method_average'] = df['Number_legs'].rank(method='average')
df['method_min'] = df['Number_legs'].rank(method='min')
df['method_max'] = df['Number_legs'].rank(method='max')
df['method_first'] = df['Number_legs'].rank(method='first')
df['method_dense'] = df['Number_legs'].rank(method='dense')

na_option: {‘keep', ‘top', ‘bottom'}, default ‘keep'
df['na_keep'] = df['Number_legs'].rank(na_option='keep')
df['na_top'] = df['Number_legs'].rank(na_option='top')
df['na_bottom'] = df['Number_legs'].rank(na_option='bottom')

ascending: 升序为True, 降序为False

df['asc_True'] = df['Number_legs'].rank(method='min', ascending=True)
df['asc_False'] = df['Number_legs'].rank(method='min', ascending=False)

pct: 是否显示百分比

df['pct_True'] = df['Number_legs'].rank(method='min', pct=True)
df['pct_False'] = df['Number_legs'].rank(method='min', pct=False)

分组排序

pandas.core.groupby.GroupBy.rank 官方文档

Example:

df = pd.DataFrame(
    {"group": ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"],
      "value": [2, 4, 2, 3, 5, 1, 2, 4, 1, 5],}
)

for method in ['average', 'min', 'max', 'dense', 'first']:
    df[f'{method}_rank'] = df.groupby('group')['value'].rank(method)

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文