【问题标题】:Randomly allot values to the rows in python将值随机分配给python中的行
【发布时间】:2021-03-23 12:53:17
【问题描述】:

我有以下输入表(y):

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

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

parameter1 parameter2 parameter3
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 的第一行值。我该如何解决这个问题?

【问题讨论】:

  • 您想根据parameter1 中的值随机分配A1A9 的值吗?
  • 您的代码在使用parameter1 列排序后看起来很好。
  • 是的,基于参数1

标签: python pandas random randomized-algorithm


【解决方案1】:

Series.sample

我们可以使用samplefrac=1parameter1 列中的值进行采样,然后使用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

【讨论】:

  • 这样一个优雅的解决方案。只是一个快速的问题。我无法意识到 addradd 方法之间的区别。
  • 谢谢@ashkangh。为了更好地理解让我们考虑一个例子,如果你想添加 series + some value 那么你通常会使用 add 但如果你想添加 some value + series 在这种情况下你会使用radd .
  • 哦。惊人的!!如果我错了,请纠正我。这两种方法也可以应用于strings,如果是这样,它们会连接两个各自的值。对吗?
  • addradd都是pandasSeries对象的方法,所以你需要Series对象来使用这些方法。
  • 非常感谢您的回复!当我尝试对参数 1 进行采样和连接时,我无法在 A1-A9 之间获得参数 3,而是生成随机数。我该如何纠正?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多