繁体   English   中英

如何用排名替换 Pandas 行中的值

[英]How to Replace Values in Pandas Rows with Ranks

我有一个 dataframe 有多个列,每个列都有自己的值。

data = {'name' : ['bill', 'joe', 'steve'],
    'test1' : [7, 75, 85],
    'test2' : [35, 45, 83],
     'test3' : [51, 61, 45]}
df = pd.DataFrame(data)

    name  test1  test2  test3
0   bill      7     35     51
1    joe     75     45     61
2  steve     85     83     45

我想用行中的相对排名而不是实际值替换某些列中的值。 output 如下。

    name  test1  test2  test3
0   bill      3     2      1
1    joe      1     3      2
2  steve      1     2      3

有没有办法做到这一点?

您可以在轴 1 上使用DataFrame.rank

df = df.assign(**df.iloc[:, 1:].rank(axis = 1, ascending = False).astype(int))

    name    test1   test2   test3
0   bill    3       2       1
1   joe     1       3       2
2   steve   1       2       3
>>> df.rank("columns", ascending=False)
   test1  test2  test3
0    3.0    2.0    1.0
1    1.0    3.0    2.0
2    1.0    2.0    3.0

>>> rankcols = ["test1", "test2", "test3"]
>>> df[rankcols] = df[rankcols].rank("columns", ascending=False).astype(int)
>>> df
    name  test1  test2  test3
0   bill      3      2      1
1    joe      1      3      2
2  steve      1      2      3

脑筋急转弯 Numpy 赋值

a = np.argsort(df.iloc[:, 1:].to_numpy(), axis=1)
n, m = a.shape
b = np.empty_like(a)
c, d = np.mgrid[:n, :m]
b[c, a] = m - d

df.iloc[:, 1:] = b

df

    name  test1  test2  test3
0   bill      3      2      1
1    joe      1      3      2
2  steve      1      2      3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM