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

Pandas批量处理销售列:含RB+的数值乘1000并清除文本

处理Pandas DataFrame中sold列的千位标记转换

需求分析

需要将sold列中带有RB+/RB(印尼语中表示“千”)的字符串转换为实际数值:

  • 包含RB+/RB的内容:提取数字部分,替换逗号为小数点后乘以1000
  • 普通数字:保持原数值不变

解决方案代码

方法1:分步清晰版

import pandas as pd
import numpy as np

# 1. 清理字符串:移除RB/RB+后缀,替换逗号为小数点
df['sold_temp'] = df['sold'].str.replace(r'RB\+?$', '', regex=True).str.replace(',', '.')

# 2. 转换为数值类型
df['sold_temp'] = pd.to_numeric(df['sold_temp'], errors='coerce')

# 3. 根据原列是否含RB标记,决定是否乘以1000
df['sold'] = np.where(
    df['sold'].str.contains(r'RB', na=False),
    df['sold_temp'] * 1000,
    df['sold_temp']
)

# 4. 可选:删除临时列,转换为整数(如果不需要小数)
df = df.drop('sold_temp', axis=1)
df['sold'] = df['sold'].astype(int)

方法2:链式简洁版

import pandas as pd
import numpy as np

df['sold'] = (
    df['sold']
    # 移除RB/RB+后缀,替换逗号为小数点
    .str.replace(r'RB\+?$', '', regex=True)
    .str.replace(',', '.')
    # 转换为数值
    .pipe(pd.to_numeric, errors='coerce')
    # 根据原标记判断是否乘1000
    .mul(np.where(df['sold'].str.contains(r'RB', na=False), 1000, 1))
    # 转整数(可选)
    .astype(int)
)

代码说明

  1. 正则替换:r'RB\+?$'匹配RB或RB+后缀,确保两种格式都能被清理;逗号替换为小数点是因为印尼语使用逗号作为小数分隔符。
  2. 数值转换:pd.to_numeric将清理后的字符串转为数值类型,errors='coerce'会将无法转换的值设为NaN(可根据需求调整)。
  3. 条件乘法:np.where通过原sold列的标记判断,对千位标记的数值放大1000倍,普通数值保持不变。
  4. 整数转换:如果业务需求不需要小数,最后转为整数类型即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:00:59