Skip to main content
 首页 » 编程设计

python之pandas之按值选择/屏蔽前 n 个元素

2025年05月04日13EasonJim

从一个数据帧开始:

I,a,b,c,d,e,f 
A,1,3,5,6,4,2 
B,3,4,7,1,0,0 
C,1,3,5,2,0,7 

我想通过保持列顺序的值来保留/屏蔽行中的前三个元素,以便生成的数据框显示为:

I,a,b,c,d,e,f 
A,0,0,5,6,4,0 
B,3,4,7,0,0,0 
C,0,3,5,0,0,7 

到目前为止,我已经能够使用以下方法对数据框进行排序:

a = df.values 

和

a.sort(axis=1) 

这样:

[[1 1 2 3 4 5] 
 [0 0 1 1 3 4] 
 [0 1 1 3 5 7]] 

获取排序的 numpy 数组,丢失有关列的信息。

请您参考如下方法:

您可以按行排列值,然后过滤它们并调用 fillna:

In [248]: 
df[df.rank(axis=1, method='min')>3].fillna(0) 
 
Out[248]: 
   I  a  b  c  d  e  f 
0  0  0  0  5  6  4  0 
1  0  3  4  7  0  0  0 
2  0  0  3  5  0  0  7 

然后您可以将其连接回去以返回“I”列:

In [268]: 
pd.concat([df['I'], df[df.rank(axis=1, method='min')>3].fillna(0)[df.columns[1:]]], axis=1) 
 
Out[268]: 
   I  a  b  c  d  e  f 
0  A  0  0  5  6  4  0 
1  B  3  4  7  0  0  0 
2  C  0  3  5  0  0  7 

中间 dfs 的输出:

In [269]: 
 
df.rank(axis=1, method='min') 
Out[269]: 
   a  b  c  d  e  f 
0  1  3  5  6  4  2 
1  4  5  6  3  1  1 
2  2  4  5  3  1  6 
In [270]: 
 
df.rank(axis=1, method='min')>3 
Out[270]: 
       a      b     c      d      e      f 
0  False  False  True   True   True  False 
1   True   True  True  False  False  False 
2  False   True  True  False  False   True