熊猫python从另一个列值从列表列中随机选择值

时间:2019-09-26 09:32:43

标签: python pandas list slice

我有一个数据框,其中一列包含列表值,而另一列仅包含列表中的一项。我想通过列id中的条件从列canceled中选择值,然后使用所选值创建另一列C
 已取消列是已取消代码的数量。 我需要将canceled更改为int,并将它们与被取消的数字切成I列,然后从I列返回一个随机数。即说代码11AS,我将从数组中随机选择1个ID,并创建另一个ID已取消的行。对于自22以来的代码22AS,我将不会对其进行切片,因此不会在新创建的列中返回任何值,因此它将涉及所有行。

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是我的DataFrame。

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

1 个答案:

答案 0 :(得分:1)

如何将applyrandom.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
)