将随机样本列添加到数据框

时间:2020-04-06 15:34:12

标签: python pandas dataframe random

说我有一个像这样的表:

| Name   | Age |
|--------|-----|
| Bob    | 2   |
| John   | 3   |
| Tim    | 4   |
| Ben    | 5   |
| Ella   | 4   |
| Sophie | 5   |
| Grace  | 6   |
| Bill   | 34  |
| Ron    | 23  |
| Harry  | 2   |

我如何添加新列以随机选择10%的行并添加带有True的新列?然后将其余设置为False。这样吗

| Name   | Age |       |
|--------|-----|-------|
| Bob    | 2   | False |
| John   | 3   | False |
| Tim    | 4   | False |
| Ben    | 5   | True  |
| Ella   | 4   | False |
| Sophie | 5   | False |
| Grace  | 6   | False |
| Bill   | 34  | False |
| Ron    | 23  | False |
| Harry  | 2   | False |

2 个答案:

答案 0 :(得分:1)

您可以使用熊猫的sample函数:

df.loc[df.sample(frac=0.1).index, "sample_column"] = True
df["sample_column"] = df["sample_column"].fillna(False)

答案 1 :(得分:0)

使用pandas.DataFrame.sample

df['flag'] = df.index.isin(df.sample(frac=0.1, random_state=1).index)

OR

df['flag'] = False
df.loc[df.sample(frac=0.1, random_state=1).index, 'flag'] = True

样本输出

>>> df
      Name   Age   flag
1      Bob   2.0  False
2     John   3.0  False
3      Tim   4.0   True
4      Ben   5.0  False
5     Ella   4.0  False
6   Sophie   5.0  False
7    Grace   6.0  False
8     Bill  34.0  False
9      Ron  23.0  False
10   Harry   2.0  False