猿问

替换边上的数字

我有一个只有 0 和 127 的数据帧。如示例中所示,127s 聚集在一起。


df = DataFrame({'f1' : [0,0,0,0,0,0],

'f2' : [0,0,0,0,0,0],

'f3' : [0,0,127,127,0,0],

'f4' : [0,127,127,127,0,0],

'f5' : [0,127,127,127,127,0],

'f6' : [0,127,127,127,127,0],

'f7' : [0,0,127,127,127,0],

'f8' : [0,0,127,127,0,0],

'f9' : [0,0,127,0,0,0],

'f10' : [0,0,0,0,0,0]

})


    f1  f2   f3   f4   f5   f6   f7   f8   f9  f10

0   0   0    0    0    0    0    0    0    0    0

1   0   0    0  127  127  127    0    0    0    0

2   0   0  127  127  127  127  127  127  127    0

3   0   0  127  127  127  127  127  127    0    0

4   0   0    0    0  127  127  127    0    0    0

5   0   0    0    0    0    0    0    0    0    0

给定一个数字列表num_of_cells_to_del,我想随机清除特定列中的许多单元格randomly from top or bottom。


num_of_cells_to_del = [0,0,0,1,1,2,2,1,0,0]

结果:


        f1  f2  f3  f4  f5  f6  f7  f8  f9  f10

   0    0   0   0   0   0   0   0   0   0   0

   1    0   0   0   0   127 0   0   0   0   0

   2    0   0   127 127 127 0   0   0   127 0

   3    0   0   127 127 127 127 127 127 0   0

   4    0   0   0   0   0   127 0   0   0   0

   5    0   0   0   0   0   0   0   0   0   0


婷婷同学_
浏览 132回答 2
2回答

三国纷争

我的解决方案for col, cells in zip(df.columns, num_of_cells_to_del):&nbsp; col_vals = df[col].values&nbsp; non_zero = np.where(col_vals == 127)[0] # find which indices have 127&nbsp; if len(non_zero) < cells: # can't delete more that what's present!&nbsp; &nbsp; raise Exception('Not enough 127 in the column!')&nbsp; if len(non_zero) == 0:&nbsp; &nbsp; continue&nbsp; replace_indices = np.random.choice(non_zero, size=cells, replace=False) # choose random indices to delete&nbsp; col_vals[replace_indices] = 0&nbsp; df[col] = col_vals
随时随地看视频慕课网APP

相关分类

Python
我要回答