You need to enable JavaScript to run this app. 如何不使用循环创建每行含连续递增整数至指定值的pandas DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用循环创建每行含连续递增整数至指定值的pandas DataFrame

无循环实现方案

完全可以用numpy向量化广播实现,没有任何显式Python循环,性能远高于传统循环写法,示例代码如下:

import pandas as pd
import numpy as np

# 输入的整数数组
input_arr = np.array([5, 3, 7, 6, 4])
# 计算所需的最大列数
max_col_cnt = input_arr.max()

# 广播生成布尔掩码:第i行第j列值为True当且仅当 1+j <= input_arr[i]
mask = input_arr[:, None] >= np.arange(1, max_col_cnt + 1)
# 填充数值,不符合条件的位置默认补NaN,可按需替换为其他值
result_arr = np.where(mask, np.arange(1, max_col_cnt + 1), np.nan)

# 转成DataFrame
df = pd.DataFrame(result_arr)

效果验证

针对你给出的示例数组,生成的DataFrame结构如下:

  • 第1行:[1, 2, 3, 4, 5, NaN, NaN]
  • 第2行:[1, 2, 3, NaN, NaN, NaN, NaN]
  • 第3行:[1, 2, 3, 4, 5, 6, 7]
  • 第4行:[1, 2, 3, 4, 5, 6, NaN]
  • 第5行:[1, 2, 3, 4, NaN, NaN, NaN]

完全符合你的需求。如果不需要保留NaN,可将代码中的np.nan替换为你需要的填充值(比如0、空字符串等)。

内容的提问来源于stack exchange,提问作者J. Chapman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 11:24:03