Pandas 根据条件列对行的子集进行排名

Pandas rank subset of rows based on condition column

我想按 score 对以下数据框进行排名,仅针对 conditionFalse 的行。其余的应该有 NaN.

的排名
df=pd.DataFrame(np.array([[34, 65, 12, 98, 5],[False, False, True, False, False]]).T, index=['A', 'B','C','D','E'], columns=['score', 'condition'])

具有(降序)条件排名的所需输出为:

   score  condition  cond_rank
A     34          0     3 
B     65          0     2
C     12          1    NaN
D     98          0     1
E      5          0     4

我知道 pd.DataFrame.rank() 可以处理 NaN 正在排序的值,但是如果条件是针对另一个 column/series,最有效的方法是什么实现这个?

您可以按条件列过滤 rank:

df['new'] = df.loc[~df['condition'].astype(bool), 'score'].rank()
print (df)
   score  condition  new
A     34          0  2.0
B     65          0  3.0
C     12          1  NaN
D     98          0  4.0
E      5          0  1.0

这是 where + rank。确保指定 ascending=False 否则你会得到不正确的输出。


df['score'].where(df['condition'].eq(0)).rank(ascending=False)

A    3.0
B    2.0
C    NaN
D    1.0
E    4.0
Name: score, dtype: float64