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

Dataframe指定列数据清洗:先移除末尾.0再删除所有点号

Pandas DataFrame特定列数据清洗:移除末尾.0并删除所有点号

需求说明

需要对DataFrame的指定列执行两步清洗操作:

  • 移除字段中所有末尾的.0(包括逗号分隔的单个元素末尾)
  • 删除列内所有的.符号

输入示例

id Zip              Contact
1  12345.0,67890.0  123.213.1234
2  5.567.4          1212121212.0
3  11111
4  22222.           999.999.9999,7897897897.0

输出示例

id Zip              Contact
1  12345,67890      1232131234
2  55674            1212121212
3  11111
4  22222            9999999999,7897897897

解决方案

使用Pandas的字符串处理方法结合正则表达式,精准匹配并替换目标内容:

import pandas as pd

# 构造输入DataFrame
data = {
    'id': [1, 2, 3, 4],
    'Zip': ['12345.0,67890.0', '5.567.4', '11111', '22222.'],
    'Contact': ['123.213.1234', '1212121212.0', None, '999.999.9999,7897897897.0']
}
df = pd.DataFrame(data)

def clean_column(column):
    # 第一步:移除所有位于元素末尾的.0(支持逗号分隔的多个元素)
    column = column.str.replace(r'\.0(?=,|$)', '', regex=True)
    # 第二步:删除列中所有的.符号
    column = column.str.replace('.', '', regex=False)
    return column

# 对指定列应用清洗逻辑
df['Zip'] = clean_column(df['Zip'])
df['Contact'] = clean_column(df['Contact'])

print(df)

逻辑说明

  • r'\.0(?=,|$)':使用正向预查匹配,仅替换紧跟逗号或字段结尾的.0,确保逗号分隔的每个元素都能被正确处理,不会误删中间的.0(如果存在)。
  • .str.replace('.', '', regex=False):直接替换所有.为空字符串,关闭正则模式避免转义问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:57:36