将列的百分比设置为0(pandas)

问题描述 投票:2回答:3

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

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

我现在想要将B的第一个和最后20%的df设置为0。

  A   B  
  1   0
  2   7
  3   8
  4   4
  5   0
python python-2.7 pandas dataframe
3个回答
1
投票

使用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'>

EDIT1

另一个解决方案是首先转换为密集然后转换回:

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

0
投票

你可以做:

num_rows = round(len(df)*0.2)

df.loc[(df.index<num_rows) | (df.index[::-1]<num_rows), 'B'] = 0

df
Out[89]: 
   A  B
0  1  0
1  2  7
2  3  8
3  4  4
4  5  0

0
投票

你可以这样做:

x = 20  # percentage of the first and last rows
y = float(len(df.index))
z = int(round(y/100 *x))
h = int(y-z)
df['B'][:z]=0
df['B'][h:]=0
© www.soinside.com 2019 - 2024. All rights reserved.