【问题标题】:Add new pandas DataFrame column whose values are an array of random numbers with length gleaned from another column添加新的 pandas DataFrame 列,其值是一个随机数数组,长度从另一列收集
【发布时间】:2020-04-17 06:56:25
【问题描述】:

我有以下虚拟数据的DataFrame

data = { 'user_id': np.random.randint(1000000, 10000000, size=(10)), 'week': np.random.randint(1, 10, size=(10)) }
df = pd.DataFrame(data = data)

我想添加一个新列,其值是长度为week 的数组(这些数组包含随机值)。这些都不起作用

df.loc[:,'inputs'] = np.random.randint(0, 28, size=(10))

(为每个 DataFrame 单元格提供一个整数,而不是它们的数组)

df.loc[:,'inputs'] = np.random.randint(0, 28, size=(df['week']))

ValueError:值的长度与索引的长度不匹配

df.loc[:,'inputs'] = np.random.randint(0, 28, size=(10, df['week']))

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

这些显然都是错误的,但我看不出如何创建一个新列,其条目是每个数组,其中这些数组的长度取决于同一行中另一列的值。

【问题讨论】:

  • 语言标签请
  • @MadPhysicist,我认为语言标签会产生误导,这不是一般的 Python 问题,它特定于熊猫。我将编辑标题以使其更清晰
  • 没有 python 就无法使用 pandas。好吧,至少不是正常的方式。
  • 确实如此,但是在没有 pandas 的情况下编写 Python 的方法有很多。这个问题只对编写 pandas 的人感兴趣,而不是所有 Python 程序员,因此标签。

标签: pandas numpy


【解决方案1】:

通过week 数字对数组使用列表推导:

df['inputs'] = [np.random.randint(0, 28, size=x) for x in df['week']]
print (df)
   user_id  week                             inputs
0  9168288     4                     [15, 5, 10, 9]
1  2765768     7          [21, 26, 6, 6, 22, 21, 4]
2  2948278     6               [6, 14, 4, 2, 3, 20]
3  9302275     1                               [23]
4  5737115     5                 [1, 20, 9, 19, 18]
5  5214343     9  [16, 25, 1, 10, 2, 23, 1, 16, 18]
6  9332184     7          [8, 27, 14, 8, 14, 11, 5]
7  1569483     5                 [6, 19, 3, 10, 16]
8  2931319     2                            [0, 15]
9  2126334     2                           [20, 22]

【讨论】:

  • 感谢您的尝试,但这不是我想要的。我希望“输入”列中的每个条目都是长度为 df['week'] 的数组
  • @dumbledad - 这是你需要的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 2017-03-07
  • 2018-08-26
  • 2019-04-10
  • 2020-01-26
  • 1970-01-01
相关资源
最近更新 更多