Python 如何用列组替换行中的值
我有一个包含多个列的数据框架,每个列都有自己的值Python 如何用列组替换行中的值,python,pandas,Python,Pandas,我有一个包含多个列的数据框架,每个列都有自己的值 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
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
我想用行中的相对秩而不是实际值来替换某些列中的值。结果如下
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
您可以在轴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
心不在焉的Numpy作业
心不在焉的Numpy作业
你从哪里得到相对值?在你的例子中,它们似乎并不一致。UPD:我知道了,低值得到3,高值得到1。你从哪里得到相对值?在你的例子中,它们似乎并不一致。UPD:我知道了,较低的值是3,较高的值是1。我喜欢双splat(-:我喜欢双splat(-:
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