【问题标题】:create a list of lists where the length of the list is mentioned in another column创建一个列表列表,其中列表的长度在另一列中提到
【发布时间】:2014-04-04 07:28:42
【问题描述】:

我的 df 是这样的;

data = pd.DataFrame({'count':[1,2,4,5,8,1,3]})

如何创建一个名为“lists”的新列,其中包含一个随机列表,其中列表的长度是“count”列中的值?像这样的...

data = pd.DataFrame({'count':[1,2,4,5,8,1,3],
                     'lists': [[1],[34,56],[25,65,1,4],[33,37,89,12,11],[45,56,78,98,12,2,3,4],[234],[23,456,765]]

【问题讨论】:

  • 您为什么要这样做?这将是非常低效的
  • 但是我遇到了需要我这样做的情况
  • @EdChum 是的。我想这对于 df 来说是非常低效的处理

标签: python pandas


【解决方案1】:

你可以试试:

data['list'] = data.applymap(lambda x: random.sample(xrange(100), x))

或者,

data['list'] = data['count'].apply(lambda x: pd.np.random.random_integers(1, 100, x) )

【讨论】:

  • 生成一个随机数列表怎么样?
  • @richie 查看更新后的答案。而且,当然,您需要导入随机
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 2012-06-29
  • 1970-01-01
  • 2019-08-14
  • 2019-05-27
  • 2018-06-20
相关资源
最近更新 更多