我有一个只有 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 f100 0 0 0 0 0 0 0 0 0 01 0 0 0 127 127 127 0 0 0 02 0 0 127 127 127 127 127 127 127 03 0 0 127 127 127 127 127 127 0 04 0 0 0 0 127 127 127 0 0 05 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
2 回答
三国纷争
TA贡献1804条经验 获得超7个赞
我的解决方案
for col, cells in zip(df.columns, num_of_cells_to_del):
col_vals = df[col].values
non_zero = np.where(col_vals == 127)[0] # find which indices have 127
if len(non_zero) < cells: # can't delete more that what's present!
raise Exception('Not enough 127 in the column!')
if len(non_zero) == 0:
continue
replace_indices = np.random.choice(non_zero, size=cells, replace=False) # choose random indices to delete
col_vals[replace_indices] = 0
df[col] = col_vals
添加回答
举报
0/150
提交
取消