python pandas : assign control vs. 根据 % 随机处理分组

标签 python pandas dataframe pandas-groupby experimental-design

我正在进行一项实验设计,我需要根据预先存在的分组按百分比将数据框 df 分成对照组和治疗组。

这是数据框 df:

df.head()

customer_id | Group | many other columns
ABC             1
CDE             1
BHF             2
NID             1
WKL             2
SDI             2

pd.pivot_table(df,index=['Group'],values=["customer_id"],aggfunc=lambda x: len(x.unique()))

Group 1  : 55394
Group 2  : 34889

现在我需要在 df 中添加一个标有“Flag”的列。 对于第 1 组,我想随机分配 50%“控制”和 50%“测试”。 对于第 2 组,我想随机分配 40% 的“控制”和 60% 的“测试”。

我正在寻找的输出:

customer_id | Group | many other columns | Flag
ABC             1                          Test
CDE             1                          Control
BHF             2                          Test
NID             1                          Test
WKL             2                          Control
SDI             2                          Test

最佳答案

我们可以使用numpy.random.choice()方法:

In [160]: df['Flag'] = \
     ...: df.groupby('Group')['customer_id']\
     ...:   .transform(lambda x: np.random.choice(['Control','Test'], len(x), 
                                                  p=[.5,.5] if x.name==1 else [.4,.6]))
     ...:

In [161]: df
Out[161]:
  customer_id  Group     Flag
0         ABC      1  Control
1         CDE      1     Test
2         BHF      2     Test
3         NID      1  Control
4         WKL      2     Test
5         SDI      2  Control

更新:

In [8]: df
Out[8]:
  customer_id  Group
0         ABC      1
1         CDE      1
2         BHF      2
3         NID      1
4         WKL      2
5         SDI      2
6         XXX      3
7         XYZ      3
8         XXX      3

In [9]: d = {1:[.5,.5], 2:[.4,.6], 3:[.2,.8]}

In [10]: df['Flag'] = \
    ...: df.groupby('Group')['customer_id'] \
    ...:   .transform(lambda x: np.random.choice(['Control','Test'], len(x), p=d[x.name]))
    ...:

In [11]: df
Out[11]:
  customer_id  Group     Flag
0         ABC      1     Test
1         CDE      1     Test
2         BHF      2  Control
3         NID      1  Control
4         WKL      2  Control
5         SDI      2     Test
6         XXX      3     Test
7         XYZ      3     Test
8         XXX      3     Test

关于python pandas : assign control vs. 根据 % 随机处理分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46548404/

相关文章:

python - 如何使用 pandas 返回前 10 个频繁列值?

python - 根据行号列表合并数据帧

python - 数据框:添加具有其他列组平均值的列

python - Selenium 无法从workera.ai 中找到元素

python - 提取数据帧列名和行索引中的特定值

Python正则表达式匹配字符串末尾的标点符号

python - 在 Pandas 数据框中替换大于 1 的值

python - 如何使用 Pandas 将一列与另外两列中的唯一值求和?

python - 遍历 Django 项目中的每个模型

python - Seaborn 的 No numeric types to aggregate 错误