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

如何将DataFrame虚拟列的1替换为与前一个1的索引距离

实现多列虚拟列的1替换为索引距离的方案

核心思路

对DataFrame的每一列独立处理:

  • 定位列中所有值为"1"(或数值1)的索引位置
  • 首个"1"替换为"A"
  • 后续每个"1"替换为当前索引与前一个"1"索引的差值
  • 非"1"的位置保持原数值不变

代码实现

1. 构造示例数据

先创建一个包含多列虚拟变量的示例DataFrame(如果你的数据是字符串类型的"1",看后面的适配版):

import pandas as pd

# 数值型1的示例DataFrame
df = pd.DataFrame({
    'col1': [0, 1, 0, 0, 1, 0, 1],
    'col2': [1, 0, 1, 0, 0, 1, 0],
    'col3': [0, 0, 0, 1, 0, 0, 0]
})

2. 定义列处理函数

这个函数会单独处理每一列,完成替换逻辑:

def process_single_column(col):
    # 获取当前列中所有值为1的索引
    ones_indices = col[col == 1].index.tolist()
    if not ones_indices:
        return col  # 列中没有1时直接返回原列
    
    # 复制原列作为结果容器
    processed_col = col.copy()
    # 首个1替换为"A"
    processed_col[ones_indices[0]] = "A"
    # 遍历后续的1,计算与前一个1的索引差
    for idx in range(1, len(ones_indices)):
        index_diff = ones_indices[idx] - ones_indices[idx-1]
        processed_col[ones_indices[idx]] = index_diff
    
    return processed_col

3. 应用到所有列

用apply方法将处理函数批量应用到DataFrame的每一列:

df_target = df.apply(process_single_column)

处理后的df_target结果:

col1col2col3
00A0
1A00
2010
300A
4300
5030
6200

适配字符串类型的"1"

如果你的DataFrame中存储的是字符串格式的"1",只需修改处理函数的判断条件和结果类型:

def process_str_column(col):
    ones_indices = col[col == "1"].index.tolist()
    if not ones_indices:
        return col
    
    processed_col = col.copy()
    processed_col[ones_indices[0]] = "A"
    for idx in range(1, len(ones_indices)):
        index_diff = str(ones_indices[idx] - ones_indices[idx-1])
        processed_col[ones_indices[idx]] = index_diff
    
    return processed_col

# 示例字符串型DataFrame
df_str = pd.DataFrame({
    'col1': ["0", "1", "0", "0", "1", "0", "1"],
    'col2': ["1", "0", "1", "0", "0", "1", "0"],
    'col3': ["0", "0", "0", "1", "0", "0", "0"]
})

df_target_str = df_str.apply(process_str_column)

方案优势

  • 自动适配任意列数,无需针对单列重复编写代码
  • 每列独立处理,互不干扰
  • 兼容数值型和字符串型的"1",可根据实际数据调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:41:32