【问题标题】:Groupby and create a new column by randomly assign multiple strings into it in PandasGroupby并通过在Pandas中随机分配多个字符串来创建一个新列
【发布时间】:2020-08-30 23:51:09
【问题描述】:

假设我有学生信息idageclass,如下所示:

   id  age  class
0   1   23    a
1   2   24    a
2   3   25    b
3   4   22    b
4   5   16    c
5   6   16    d

我想通过class 分组并通过随机分配math, art, business, science 来创建一个名为major 的新列,这意味着对于同一类,主要字符串是相同的。

我们可能需要使用apply(lambda x: random.choice..) 来实现这一点,但我不知道该怎么做。谢谢你的帮助。

预期输出:

   id  age     major  class
0   1   23       art    a
1   2   24       art    a
2   3   25   science    b
3   4   22   science    b
4   5   16  business    c
5   6   16      math    d

【问题讨论】:

  • 是的,抱歉,我还没有找到这个。

标签: python-3.x pandas


【解决方案1】:

使用numpy.random.choiceDataFrame 长度的值数:

df['major'] = np.random.choice(['math', 'art', 'business', 'science'], size=len(df))
print (df)
   id  age     major
0   1   23  business
1   2   24       art
2   3   25   science
3   4   22      math
4   5   16   science
5   6   16  business

编辑:对于每个组的相同主要值,请使用 Series.map 和字典:

c = df['class'].unique()
vals = np.random.choice(['math', 'art', 'business', 'science'], size=len(c))

df['major'] = df['class'].map(dict(zip(c, vals)))
print (df)
   id  age class     major
0   1   23     a  business
1   2   24     a  business
2   3   25     b       art
3   4   22     b       art
4   5   16     c   science
5   6   16     d      math

【讨论】:

  • 谢谢,我已经修改了我的问题,请您重新看一下好吗?
猜你喜欢
  • 1970-01-01
  • 2022-11-23
  • 2014-10-26
  • 2015-09-13
  • 2022-09-27
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 2021-10-09
相关资源
最近更新 更多