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

Pandas如何将同一行Price列非整数值移动到Description列

实现方法

核心逻辑是先识别Price列中无法转换为整数的异常值,将这类值写入对应行的Description列,再把Price列对应位置置为空值,最后统一转换Price列为数值类型即可。

  • 第一步:导入依赖、构造测试数据
import pandas as pd
import numpy as np

# 构造示例DataFrame
df = pd.DataFrame({
    'id': [1, 2, 3, 4, 5],
    'Description': ['Test Only', 'Data test', 'Sample', 'Sample Onces', 'Sample'],
    'Price': ['1254', 'Fresher', '3569', 'Code test', '245'],
    'Unit': [12, 4, 1, np.nan, 2]
})
  • 第二步:识别Price列中的非整数行
    通过异常捕获判断值是否可转为整数,生成异常行掩码:
def check_non_int(val):
    try:
        int(val)
        return False
    except (ValueError, TypeError):
        return True

# 标记Price列值为非整数的行
error_mask = df['Price'].apply(check_non_int)
  • 第三步:按规则处理数据
# 将非整数的Price值写入对应行Description列
df.loc[error_mask, 'Description'] = df.loc[error_mask, 'Price']
# 异常行Price位置置为NaN
df.loc[error_mask, 'Price'] = np.nan
# 统一转换Price列为可空整数类型,避免浮点数后缀.0
df['Price'] = pd.to_numeric(df['Price'], errors='coerce').astype('Int64')

处理后输出结果与预期完全一致:

id Description Price  Unit
0   1   Test Only  1254  12.0
1   2     Fresher  <NA>   4.0
2   3      Sample  3569   1.0
3   4   Code test  <NA>   NaN
4   5      Sample   245   2.0

如果需要保留原Description列的内容,只需要把赋值Description的代码改为拼接格式即可:
df.loc[error_mask, 'Description'] = df.loc[error_mask, 'Description'] + ' ' + df.loc[error_mask, 'Price']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 02:01:24