Python 将列的百分比设置为0(熊猫)

Python 将列的百分比设置为0(熊猫),python,python-2.7,pandas,dataframe,Python,Python 2.7,Pandas,Dataframe,我有一个熊猫数据框,我想将某个列的百分比设置为0。假设df有两列 A B 1 6 2 7 3 8 4 4 5 9 现在,我想将df的第一个和最后20%的B设置为0 A B 1 0 2 7 3 8 4 4 5 0 用于连接第一个和最后一个位置,然后通过更改值,对于列的位置B使用: 或: 编辑: 如果可以将相同类型的值转换为numpy数组,请设置值并转换回: arr = df.values

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

  A   B  
  1   6
  2   7
  3   8
  4   4
  5   9
现在,我想将df的第一个和最后20%的B设置为0

  A   B  
  1   0
  2   7
  3   8
  4   4
  5   0
用于连接第一个和最后一个位置,然后通过更改值,对于列的位置
B
使用:

或:


编辑:

如果可以将相同类型的值转换为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'>
df = df.to_dense()
#apply solution
df = df.to_sparse()
你可以这样做:

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
你可以做:

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
num_行=圆形(长度(df)*0.2)

df.loc[(df.indexthis不是第一个和最后一个10%-它是第一个和最后一个20%确定的,谢谢!它只是一些x百分比的一个例子,但你是对的。@jkortner-hmmm,它有点复杂。一个可能的解决方案是通过
df=df.to_dense()将SPARSTAFRAME转换为稠密
,应用解决方案,然后通过
df=df.转换回\u sparse()
df = df.to_dense()
#apply solution
df = df.to_sparse()
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
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