python - 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])))
解决方案
和下面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
)
推荐阅读
- curl - SLURM:卷曲的作业无缘无故地取消了 2 卷曲 [JobState=CANCELLED 原因=无 ExitCode=0:15]
- pine-script - 如何在“过去 14 根蜡烛的时期/如何定义过去 14 根蜡烛的范围或时期?”中检查条件是真还是假?
- c++ - 怎么了?尽管#define _USE_MATH_DEFINES 和#include,M_PI 未声明错误
- java - Tomcat 9 上的 SSL Windows 认证错误
- java - 集成 Admob 的“App Open Ad”后的 IllegalStateException
- gpgpu - 使用 PGP 公钥生成指纹
- git - 在多个 Gît 存储库上同步多个 PR
- intersystems-iris - 将 IRIS 数据库拆分到多个驱动器
- matlab - 使用 matlab 的 ODE45 和 Runge-Kutta 方法对电晕进行优化控制
- java - 如果我在代码中将其与隐式等待一起使用,则显式等待不起作用