2 回答

TA贡献1887条经验 获得超5个赞
我只能这样想,但是,性能可能是问题
np.array(s.tolist())[np.arange(len(s)), np.random.randint(3, size=len(s))]
array(['c', 'e', 'i', 'k', 'n'], dtype='<U1')
一些时机
%timeit s.explode().sample(frac=1, random_state=1)
5.05 ms ± 294 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit pd.Series([np.random.choice(i) for i in s])
23.1 ms ± 184 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit np.array(s.tolist())[np.arange(len(s)), np.random.randint(3, size=len(s))]
1.63 ms ± 50.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

TA贡献1805条经验 获得超9个赞
您可以尝试explode,随机播放分解的系列,然后采样。这甚至不需要列表具有相同的长度。
(s.explode()
.sample(frac=1, random_state=1) # random_state added for repeatability, drop if needed
.groupby(level=0).head(1)
)
输出:
1 d
2 h
0 c
3 k
4 n
dtype: object
添加回答
举报