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

求助:DataFrame中字符串型十六进制值转整数及列类型设置

问题解决步骤

1. 整列变为None的原因及修复

你在使用replace时同时混用了inplace=True和赋值操作,这是错误的逻辑:当inplace=True生效时,replace方法会直接修改原DataFrame,并且返回None,你将这个None赋值给df1['sport'],导致整列被覆盖成空值。

正确写法二选一:

# 方式1:不用inplace,直接赋值接收返回结果
df1['sport'] = df1['sport'].replace('Ox0303', 771)
df1['sport'] = df1['sport'].replace('-1', 0)

# 方式2:用inplace,不额外赋值
df1['sport'].replace('Ox0303', 771, inplace=True)
df1['sport'].replace('-1', 0, inplace=True)

2. 批量处理十六进制值并转为int类型

手动逐个替换十六进制值效率极低,建议编写自定义转换函数,自动识别并转换所有十六进制字符串,同时处理-1转0的规则,最后统一转为int类型:

def convert_port(value):
    # 处理字符串类型的数值
    if isinstance(value, str):
        # 匹配数据中Ox开头的十六进制字符串
        if value.startswith('Ox'):
            # 截取Ox后的部分,按十六进制转十进制
            return int(value[2:], 16)
        # 处理-1转为0的规则
        elif value == '-1':
            return 0
        # 普通数字字符串直接转int
        else:
            return int(value)
    # 已经是数字类型的直接转int
    else:
        return int(value)

# 将函数应用到sport和dport列
df1['sport'] = df1['sport'].apply(convert_port)
df1['dport'] = df1['dport'].apply(convert_port)

# 验证转换后的数据类型
print(df1[['sport', 'dport']].dtypes)

3. 异常值兼容处理(可选)

如果数据中存在无法转换的异常值,可以在函数中添加异常捕获逻辑,避免程序报错:

import pandas as pd

def convert_port(value):
    try:
        if isinstance(value, str):
            if value.startswith(('Ox', '0x')):  # 兼容Ox和标准0x开头的十六进制
                return int(value[2:], 16)
            elif value == '-1':
                return 0
            else:
                return int(value)
        else:
            return int(value)
    except ValueError:
        # 无法转换时返回空值,后续可根据需求处理
        return pd.NA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:10:10