You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中基于另一列生成每行随机数?

解决方案

原始DataFrame

Column_1Column_2Number
UDKA12345
MAKU15445
POKA54342
UJFK91043

需求说明

新增一列Random,每行生成1到对应Number列数值之间的随机整数,且Random值不得严格大于Number。

实现代码

借助pandas的apply方法结合numpy的随机整数生成函数即可实现:

import pandas as pd
import numpy as np

# 构造原始DataFrame
df = pd.DataFrame({
    'Column_1': ['UDKA', 'MAKU', 'POKA', 'UJFK'],
    'Column_2': [1234, 1544, 5434, 9104],
    'Number': [5, 5, 2, 3]
})

# 生成Random列
df['Random'] = df['Number'].apply(lambda x: np.random.randint(1, x + 1))

代码说明

  • np.random.randint(1, x + 1):由于randint的上限为开区间,因此将x加1,确保生成的随机数范围是[1, x],满足不严格大于Number的要求。
  • apply方法会遍历Number列的每个值,为每行生成对应的随机数。

示例结果

Column_1Column_2NumberRandom
UDKA123454
MAKU154452
POKA543421
UJFK910432

内容的提问来源于stack exchange,提问作者Carola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 15:40:27