1

我有以下输入表(y):

参数1 参数2
1 12
2 23
3 66
4 98
5 90
6 14
7 7
8 56
9 1

我想随机分配从 A1 到 A9 的值。输出表应如下所示:

参数1 参数2 参数3
1 12 A5
2 23 A2
3 66 A4
4 98 A8
5 90 A3
6 14 A7
7 7 A1
8 56 A9
9 1 A6
n = 9

TGn = round(len(y)/n)
idx = set(y.index // TGn)

y = y.apply(lambda x: x.sample(frac=1,random_state=1234)).reset_index(drop=True)
    
treatment_groups = [f"A{i}" for i in range(1, n+1)]
y['groupAfterRandomization'] = (y.index // TGn).map(dict(zip(idx, treatment_groups)))

我无法填充它打印为 NaN 的第一行值。我该如何解决这个问题?

4

1 回答 1

1

Series.sample

我们可以使用samplewithfrac=1对列中的值进行采样,parameter1然后使用radd将前缀A与采样值连接起来

df['parameter3'] = df['parameter1'].sample(frac=1).astype(str).radd('A').values

   parameter1  parameter2 parameter3
0           1          12         A2
1           2          23         A8
2           3          66         A1
3           4          98         A4
4           5          90         A9
5           6          14         A3
6           7           7         A6
7           8          56         A7
8           9           1         A5
于 2021-03-23T15:48:35.327 回答