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)