如何在单列中用 python 中的 100 替换 20% 的随机行值?

How to replace 20% random row values with 100 in python in a single column?

如何将 python 数据框中单列(评级)中的 20% 随机行值替换为 100?

尝试使用 sampleloc:

l = df['Rating'].sample(int((20/len(df))*100)).tolist()
df.loc[df['Rating'].isin(l),'Rating'] = 100
print(df)

Series.samplefrac=0.2 结合使用。然后使用 loc 到 select 这些索引并将它们的值替换为 100:

# example dataframe
import random
df = pd.DataFrame({'Col1':[random.randint(1,10) for x in range(10)],
                   'Col2':[random.randint(1,10) for x in range(10)]})
print(df)

   Col1  Col2
0     1     3
1     1     6
2     3     9
3     9     5
4    10     4
5    10     2
6    10     7
7     4     5
8    10     7
9    10     9
idx = df['Col1'].sample(frac=0.2).index
df.loc[idx, 'Col1'] = 100

   Col1  Col2
0   100     3
1     1     6
2   100     9
3     9     5
4    10     4
5    10     2
6    10     7
7     4     5
8    10     7
9    10     9

或者为了使其更通用,无需硬编码 0.2100,这是一个 returns 您想要的数据帧的函数:

def replace_sample(dataframe, column, fraction, val_replace):
    idx = dataframe[column].sample(frac=fraction).index
    dataframe.loc[idx, column] = val_replace

    return dataframe

replace_sample(df, 'Col1', 0.2, 100)

   Col1  Col2
0     2     5
1     5     1
2     4     3
3    10    10
4   100     5
5     6     7
6    10     1
7     8     8
8   100     9
9     2     7