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

如何将DataFrame列末尾的负号移至数字开头并替换列值?

解决DataFrame列末尾负号移至开头的问题

需求回顾

现有如下DataFrame:

col1      col2
 12.4      12.32
 11.4-     2.3
 2.0-      1.1

需要将col1列中末尾带负号的数值,把负号移至开头,得到目标结果:

col1      col2
 12.4      12.32
 -11.4     2.3
 -2.0      1.1

解决方案

方法1:正则替换(最简便)

利用pandas的字符串替换功能,用正则匹配末尾的负号并调整位置,一行代码搞定:

import pandas as pd

# 假设你的DataFrame是df
df['col1'] = df['col1'].str.replace(r'(\d+\.?\d*)-', r'-\1', regex=True)
  • 正则说明:(\d+\.?\d*)匹配整数或小数部分,-匹配末尾的负号;替换为-\1就是把负号移到匹配到的数字前面。

方法2:修正你的循环代码

你原来的代码只做了打印,没有收集结果,修改后可以直接赋值回列:

updated_list = []
for line in df["col1"]:
    s = str(line)
    # 判断是否以负号结尾
    if s.endswith('-'):
        updated_line = '-' + s[:-1]
    else:
        updated_line = s
    updated_list.append(updated_line)
# 替换回col1列
df['col1'] = updated_list

方法3:apply自定义函数

用apply封装逻辑,代码更简洁:

def adjust_neg_sign(s):
    s = str(s)
    return '-' + s[:-1] if s.endswith('-') else s

df['col1'] = df['col1'].apply(adjust_neg_sign)

验证结果

执行任意一种方法后,打印df就能看到目标格式的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:45:43