繁体   English   中英

将随机样本列添加到 dataframe

[英]Add a random sample column to a dataframe

假设我有一张这样的桌子:

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

我如何添加一个新列来选择随机 10% 的行并添加一个 True 的新列? 然后将 rest 设置为 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 |

您可以使用 pandas 的示例function:

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

使用pandas.DataFrame.sample

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

或者

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

样品 Output

>>> 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM