【发布时间】:2020-07-26 17:54:37
【问题描述】:
假设我有一些数据帧的子集(例如,列 a > 5)。
我想为上述子集的 70% 分配 0(例如),并保留所有其他行。
当前索引不是唯一的。
输入:
| some_index | a | b |
|-------------:|----:|----:|
| 1 | 5 | 2 |
| 2 | 4 | 5 |
| 1 | 7 | 8 |
| 2 | 10 | 11 |
输出:
| some_index | a | b |
|-------------:|----:|----:|
| 1 | 0 | 0 |
| 2 | 4 | 5 |
| 1 | 0 | 0 |
| 2 | 10 | 11 |
我想出了以下解决方案:
import pandas as pd
from random import shuffle
df2 = pd.DataFrame(np.array([[5, 2], [4, 5], [7, 8], [10, 11] ]),
columns=['a', 'b'] , index = [1, 2, 1, 2])
df2.index.name = 'some_index'
print (df2)
df2.reset_index(inplace=True) #reseting index to have a unique index
ind = df2['a'] > 4 # some condition
ind_by_cond = [row_number for row_number, bool_value in zip(ind.index, ind) if bool_value]
random.shuffle(ind_by_cond) # shuffling to make choose indexes randomly
ind_by_cond = [row_number for row_number, bool_value in zip(ind.index, ind) if bool_value]
# 0.7 is the 70% of the subset, that I would like to change
upper_limit = int(len(ind_by_cond) * 0.7)
df2.loc[ind_by_cond[:upper_limit], ['a', 'b']] = 0
df2.set_index('some_index', inplace=True) #returning original index back
print (df2)
有没有更简单优雅(pythonic)的解决方案?
附:问题不同于: Randomly assign values to subset of rows in pandas dataframe
【问题讨论】: