如何在Pandas DataFrame最后两行的随机x列中替换值?
在Pandas DataFrame最后两行随机选取x列替换值的实现方法
直接上实操代码,结合示例一步步来:
1. 准备示例数据
import pandas as pd import numpy as np # 创建5行5列的示例DataFrame df = pd.DataFrame({ 'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10], 'C': [11, 12, 13, 14, 15], 'D': [16, 17, 18, 19, 20], 'E': [21, 22, 23, 24, 25] })
2. 核心实现步骤
假设你要随机选x=2列进行替换:
x = 2 # 自定义需选取的列数 # 1. 定位最后两行的索引 last_two_indices = df.index[-2:] # 2. 从所有列中随机挑选x列 random_selected_cols = df.columns.sample(n=x) # 若需固定随机结果,可添加random_state参数,比如random_state=42 # 3. 替换值——两种常见场景 # 场景1:替换为固定值(比如0) df.loc[last_two_indices, random_selected_cols] = 0 # 场景2:替换为随机值(比如0到100的整数) df.loc[last_two_indices, random_selected_cols] = np.random.randint(0, 100, size=(2, x))
关键说明
df.index[-2:]能精准定位最后两行的索引,适配任意行数的DataFrame;df.columns.sample(n=x)是从列名中随机选x列的核心方法,和你处理列时选行的逻辑完全对应;loc索引器可直接定位「最后两行+随机列」的交叉区域,直接赋值即可完成替换,无需额外复杂操作。
内容的提问来源于stack exchange,提问作者peter_parker
相关产品推荐
相关产品推荐

