创建新列,根据其他列的排名显示值 Python

3

我有一个数据框,其中日期作为行,列中包含值。为了有一个想法,数据框看起来像下面这样:

print(df1)

            c1  c2  c3  c4
12/12/2016  38  10   1   8
12/11/2016  44  12  17  46
12/10/2016  13   6   2   7
12/09/2016   9  16  13  26

我希望创建一个规则,对df1中的每一行进行排名,并创建另一个数据框来存储一些固定值。例如,对于每行中的前2个最高值,它分配值k=5,对于最低的2个值,它显示值y=-9。

我想要得到以下的df:

            c1  c2  c3  c4
12/12/2016  5    5  -9  -9
12/11/2016  5  -9   -9   5
12/10/2016  5  -9   -9   5
12/09/2016  -9  5   -9   5

我考虑在df1上使用np.partition,但我不知道如何创建新的数据框。非常感谢任何提示!谢谢!
2个回答

5
使用ranknumpy.whereDataFrame构造函数:
arr = np.where(df.rank(axis=1, method='dense') > 2, 5, -9)

df = pd.DataFrame(arr, index=df.index, columns=df.columns)
print (df)
            c1  c2  c3  c4
12/12/2016   5   5  -9  -9
12/11/2016   5  -9  -9   5
12/10/2016   5  -9  -9   5
12/09/2016  -9   5  -9   5

0
这是一个NumPy的解决方案:
df.iloc[:] = np.where(df.values.argsort(1).argsort(1) > 1, 5, -9)

print(df)

            c1  c2  c3  c4
12/12/2016   5   5  -9  -9
12/11/2016   5  -9  -9   5
12/10/2016   5  -9  -9   5
12/09/2016  -9   5  -9   5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接