Skip to main content
 首页 » 编程设计

python之将列的百分比设置为 0( Pandas )

2025年01月19日11lexus

我有一个 pandas 数据框,我想将列的某个百分比设置为 0。假设 df 有两列。

  A   B   
  1   6 
  2   7 
  3   8 
  4   4 
  5   9 

我现在想将 df 的前 20% 和后 20% 的 B 设置为 0。

  A   B   
  1   0 
  2   7 
  3   8 
  4   4 
  5   0 

请您参考如下方法:

使用numpy.r_用于连接第一个和最后一个位置,然后按 iloc 更改值, 对于 B 列的位置使用 Index.get_loc :

N = .2 
total = len(df.index) 
#convert to int for always integer 
i = int(total * N) 
idx = np.r_[0:i, total-i:total] 
df.iloc[idx, df.columns.get_loc('B')] = 0 

或者:

N = .2 
total = len(df.index) 
i = int(total * N) 
pos = df.columns.get_loc('B') 
 
df.iloc[:i, pos] = 0 
df.iloc[total - i:, pos] = 0 

print (df) 
   A  B 
0  1  0 
1  2  7 
2  3  8 
3  4  4 
4  5  0 

编辑:

如果Sparsedataframe并且相同类型的值可以转换为 numpy 数组,设置值并转换回:

arr = df.values 
N = .2 
total = len(df.index) 
i = int(total * N) 
pos = df.columns.get_loc('B') 
idx = np.r_[0:i, total-i:total] 
 
arr[idx, pos] = 0 
print (arr) 
[[1 0] 
 [2 7] 
 [3 8] 
 [4 4] 
 [5 0]] 
 
df = pd.SparseDataFrame(arr, columns=df.columns) 
print (df) 
   A  B 
0  1  0 
1  2  7 
2  3  8 
3  4  4 
4  5  0 
 
print (type(df)) 
<class 'pandas.core.sparse.frame.SparseDataFrame'> 

编辑1:

另一种解决方案是先转换为密集,然后再转换回来:

df = df.to_dense() 
#apply solution 
df = df.to_sparse()