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

如何将DataFrame列中前三大数据随机放入指定循环位置?

实现方法

步骤拆解与代码实现

1. 初始化数据并提取关键信息

先准备测试数据,同时提取Attack列的前3大数值及其当前索引,定义需要放置的目标位置:

import pandas as pd
import numpy as np

# 测试DataFrame
d = {'Attack': [0.643,0.715,0.6826, 0.693, 0.7634, 0.7942, 0.745, 0.73, 0.755, 0.457, 0.634, 0.745]}
df = pd.DataFrame(data=d)

# 获取前3大值及对应索引
top3 = df['Attack'].nlargest(3)
top3_values = top3.values.tolist()
top3_indices = top3.index.tolist()

# 指定目标索引位置
target_indices = [0, 5, 9]

2. 随机打乱前3大数值

为了实现随机放置的需求,先打乱前3大数值的顺序:

np.random.shuffle(top3_values)

3. 执行交换与替换逻辑

遍历目标索引,根据当前值是否属于前3大,分别处理:

  • 若目标位置原数值不属于前3大:从非目标索引的前3大值位置中选一个,交换两者数值;
  • 若目标位置原数值已是前3大:直接替换为打乱后的对应数值,保证随机性。
# 复制原DataFrame,避免修改原始数据(可选操作)
df_modified = df.copy()

# 筛选出不在目标索引里的前3大值位置,作为待交换的来源
available_top_indices = [idx for idx in top3_indices if idx not in target_indices]

# 遍历目标索引和打乱后的前3大值
for target_idx, new_val in zip(target_indices, top3_values):
    current_val = df_modified.loc[target_idx, 'Attack']
    
    if current_val not in top3_values:
        # 取出一个待交换的前3大值位置
        swap_idx = available_top_indices.pop()
        # 交换数值
        df_modified.loc[target_idx, 'Attack'], df_modified.loc[swap_idx, 'Attack'] = new_val, current_val
    else:
        # 直接替换为随机后的数值
        df_modified.loc[target_idx, 'Attack'] = new_val

4. 验证结果

查看修改后的目标位置数值,确认符合要求:

print("目标索引位置的最终数值:")
print(df_modified.loc[target_indices, 'Attack'])

内容的提问来源于stack exchange,提问作者M.pillow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:55:17