pandas :仅保留前 n 个值并将其他值设置为 0 [英] pandas: Keep only top n values and set others to 0

查看:47
本文介绍了 pandas :仅保留前 n 个值并将其他值设置为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Pandas 数据框中,对于每一行,我只想保留前 N 个值并将其他所有值设置为 0.我可以遍历行并执行此操作,但我确信 python/pandas 可以在一行中优雅地执行此操作.

In a pandas dataframe, for every row, I want to keep only the top N values and set everything else to 0. I can iterate through the rows and do it but I am sure python/pandas can do it elegantly in a single line.

例如:对于 N = 2

For e.g.: for N = 2

Input:
A   B   C   D
4   10  10  6
5   20  50  90
6   30  6   4
7   40  12  9

Output:
A   B   C   D
0   10  10  0
0   0   50  90
6   30  6   0
0   40  12  0

推荐答案

Using rank 带有参数 axis=1method='min'ascending=False 为:

Using rank with parameters axis=1 and method='min' and ascending=False as:

N = 2
df = df.mask(df.rank(axis=1, method='min', ascending=False) > N, 0)

或者使用 np.wherepd.DataFramemask 方法更快:

Or using np.where with pd.DataFrame which is faster than mask method:

df = pd.DataFrame(np.where(df.rank(axis=1,method='min',ascending=False)>N, 0, df),
                  columns=df.columns)

<小时>

print(df)
   A   B   C   D
0  0  10  10   0
1  0   0  50  90
2  6  30   6   0
3  0  40  12   0

说明:

第 1 步:首先,我们需要找到行中最小的 2 个数字,以及是否需要考虑重复.因此,使用 axis=1 跨行排名和重复值将由 method='min'ascending = False 处理:>

Explanation :

Step 1: First we need to find what are the 2 smallest numbers in the row and also if there is a duplicate that need to be taken account. So, using axis=1 ranks across rows and duplicate values will be taken care by method='min' and ascending = False:

print(df.rank(axis=1, method='min', ascending=False))
     A    B    C    D
0  4.0  1.0  1.0  3.0
1  4.0  3.0  2.0  1.0
2  2.0  1.0  2.0  4.0
3  4.0  1.0  2.0  3.0

第 2 步: 其次,我们需要根据条件过滤值大于 (N) 的位置,然后使用 mask:

Step 2: Second we need to filter where the values is greater than (N) as per condition and then change those values using mask:

print(df.rank(axis=1, method='min', ascending=False) > N)
       A      B      C      D
0   True  False  False   True
1   True   True  False  False
2  False  False  False   True
3   True  False  False   True

print(df.mask(df.rank(axis=1, method='min', ascending=False) > N, 0))
   A   B   C   D
0  0  10  10   0
1  0   0  50  90
2  6  30   6   0
3  0  40  12   0

这篇关于 pandas :仅保留前 n 个值并将其他值设置为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆