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

如何随机选择Pandas DataFrame的行进行指定更新操作

解决方法

你可以按以下步骤实现需求,逻辑简单直接:

  • 先新建modified_review列,默认和原review列内容一致,这样90%的行直接保留原样
  • 随机选出10%行的索引,再针对性修改这些行的modified_review值

具体代码如下:

# 1. 初始化modified_review列,和review列内容完全一致
X_test["modified_review"] = X_test["review"]

# 2. 随机选取10%行的索引
selected_indices = X_test.sample(frac=0.1).index

# 3. 给选中的行添加指定前缀
X_test.loc[selected_indices, "modified_review"] = " abc " + X_test.loc[selected_indices, "review"]

如果需要固定随机选取的结果(比如复现实验),可以给sample方法加上random_state参数,比如sample(frac=0.1, random_state=42),这样每次运行都会选中同一批行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:20:30