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

如何从Pandas DataFrame中随机提取一行并添加至新DataFrame?

随机选取DataFrame行并添加至同结构新DataFrame的最优方法

问题根源

你之前用iloc失败,大概率是因为直接用df.iloc[random_idx]获取到的是Series类型,而非DataFrame格式的行,直接添加时会因结构不匹配导致新DataFrame只有表头无数据。

最优实现方法

方法一:用sample()直接抽样(最简洁推荐)

pandas内置的sample()方法专门用于随机抽取行/列,直接返回DataFrame格式的结果,无需手动处理索引,代码更简洁可靠:

import pandas as pd

# 假设原DataFrame为df,初始化同表头的空新DataFrame
new_df = pd.DataFrame(columns=df.columns)

# 随机抽取1行并合并到新DataFrame
random_row = df.sample(n=1)
new_df = pd.concat([new_df, random_row], ignore_index=True)

方法二:手动生成索引+保持DataFrame结构(兼容iloc场景)

如果一定要用iloc,需用双层方括号获取行,确保返回的是DataFrame而非Series:

import pandas as pd
import random

# 初始化新DataFrame
new_df = pd.DataFrame(columns=df.columns)

# 生成合法随机索引(范围0到df行数-1)
random_idx = random.randint(0, len(df)-1)
# 双层方括号获取DataFrame格式的行
random_row = df.iloc[[random_idx]]
# 合并到新DataFrame
new_df = pd.concat([new_df, random_row], ignore_index=True)

为什么推荐sample()?

  • 无需手动计算索引范围,避免因索引越界出错;
  • 原生支持抽样逻辑,代码更简洁易读;
  • 直接返回DataFrame结构,无需额外处理格式问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:47:08