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

如何移除pandas DataFrame列中'months'并将对应数值转换为年单位

Pandas A列标准化处理实现

完整可运行代码

import pandas as pd
import numpy as np

# 构造与输入一致的测试DataFrame
df = pd.DataFrame({
    'A': ['6 months', '3', '1', '6 months', '4', '1', '6 months']
})

# 列处理逻辑
a_str = df['A'].astype(str)
# 正则提取所有单元格的数字部分,转浮点型
a_num = a_str.str.extract(r'(\d+)')[0].astype(float)
# 标记原本含'months'的行
has_months = a_str.str.contains('months', na=False)
# 带months的行除以12,其余行保留原数值
df['A'] = np.where(has_months, a_num / 12, a_num)

运行输出结果

0    0.5
1    3.0
2    1.0
3    0.5
4    4.0
5    1.0
6    0.5
Name: A, dtype: float64

补充说明:

  • 当前正则适配整数时长场景,若遇到带小数的时长(如1.5 months),可将提取数字的正则替换为r'(\d+\.?\d*)'兼容小数;
  • 若需要让整数值不显示.0,可按业务需求自行调整列格式,pandas会自动适配混合数值类型的存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 18:45:03