首页 > 解决方案 > Pandas python从列表列中随机选择另一列值的值

问题描述

我有一个数据框,其中一列包含列表值,另一列包含列表中的一项。我想通过列id中的条件从列中选择值,然后使用所选值canceled创建另一列。 取消的列是取消代码的数量。我需要将 cancelled 更改为 int,然后他们将 Id 列与取消的数量切片,然后从 Id 列中返回一个随机数。即说代码 11AS 我将从数组中随机选择 1 个 id 并创建另一行取消了 id。对于从 0 开始的代码 22AS,我不会对任何内容进行切片,因此我不会在新创建的列中返回任何值,因此这将下降到所有行。C

code    canceled  id
xxx     [1.0]     [107385, 128281, 133015]
xxS     [0.0]     [108664, 110515, 113556]
ssD     [1.0]     [134798, 133499, 125396, 114298, 133915]
cvS     [0.0]     [107611]
eeS     [5.0]     [113472, 115236, 108586, 128043, 114106, 10796...
544W    [44.0]    [107650, 128014, 127763, 118036, 116247, 12802.

我试图循环并切片,但我无法得到我想要的。说px是我的数据框。

for i in px['canceled']:
    print(px['id'].str.slice(stop=int(i[0])))

标签: pythonpandaslistslice

解决方案


和下面apply的一起使用怎么样random.sample

import random

px['C'] = px.apply(
    lambda datum : random.sample(
        datum.id, k=int(datum.canceled[0])
    ),
    axis = 1
)

可能会返回(回想一下该列C是随机生成的)

code    canceled       id                                         C
xxS     [1.0]          [107385, 128281, 133015]                   [128281]
xxxxS   [0.0]          [108664, 110515, 113556]                   []
ssOD    [1.0]          [134798, 133499, 125396, 114298, 133915]   [114298]
45AS    [0.0]          [107611]                                   []
...     ...            ...                                        ...


如果int(datum.canceled[0])返回大于长度的datum.id东西,你可以做的就是datum.id完全返回。如下

def random_codes_sampler(datum):
    ids = datum.id
    nbc = int(datum.canceled[0])
    if nbc >= len(ids):
        return ids
    return random.sample(ids, k=nbc)

px['C'] = px.apply(
    random_codes_sampler, axis = 1
)

推荐阅读