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

如何用Python翻转DataFrame列中指定二进制位且不影响相邻位

翻转Pandas Series中二进制字符串的任意指定位

要实现任意指定位置的二进制位翻转且不影响其他位,核心思路是定位目标位置,单独翻转该位后再拼接前后部分。以下是两种实用方法:

方法1:apply结合自定义函数(简洁直观)

适合中小数据量,代码可读性强:

import pandas as pd

def flip_target_bit(string, target_pos):
    # target_pos为1-based的位置(比如第3位就传3)
    idx = target_pos - 1
    # 校验位置合法性,避免索引越界
    if not 0 <= idx < len(string):
        return string
    # 翻转该位:0变1,1变0
    flipped_char = '1' if string[idx] == '0' else '0'
    # 拼接前后部分得到结果
    return string[:idx] + flipped_char + string[idx+1:]

# 测试示例
s = pd.Series(["01100", "10010", "11100", "10011"])
# 翻转左数第3位
result = s.apply(flip_target_bit, target_pos=3)
print(result)

输出结果:

0    01000
1    10110
2    11000
3    10111
dtype: object

方法2:矢量化操作(高效处理大数据)

如果你的Series数据量很大,用numpy的矢量化操作替代apply,速度会快很多:

import pandas as pd
import numpy as np

s = pd.Series(["01100", "10010", "11100", "10011"])
target_pos = 3  # 左数第3位
idx = target_pos - 1

# 将字符串拆分为字符数组
char_array = np.array(s.str.split('').tolist())[:, 1:-1]
# 批量翻转指定位置的字符
char_array[:, idx] = np.where(char_array[:, idx] == '0', '1', '0')
# 重新拼接为字符串
result = pd.Series([''.join(row) for row in char_array])
print(result)

补充说明

  • 如果你需要从右数指定位置(比如倒数第1位),只需要调整索引计算:idx = len(string) - target_pos(比如倒数第1位,target_pos=1,idx就是len(string)-1)。
  • 两种方法都保留了原字符串的长度和其他位的数值,完全满足你“不影响相邻位”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:25:30