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

Pandas合并两列:含NA时保留有效ID而非返回NA的实现

解决DataFrame列拼接时NaN导致结果异常的问题

问题核心:当student_name为NaN时,Pandas中任何与NaN的字符串拼接运算都会直接返回NaN,这就是第一行结果不符合预期的原因。

下面提供几种可行的解决方法:

方法一:使用np.where做条件判断

通过判断student_name是否为空,分别返回不同的拼接结果:

import pandas as pd
import numpy as np

df = pd.DataFrame({'student_id': [71, 63, 23],
                   'student_name': [np.nan, 'Peter Andrews', 'Amy Powers'],
                   })

df['student_id_name'] = np.where(
    df['student_name'].isna(),
    df['student_id'].astype(str),
    df['student_id'].astype(str) + ' ' + df['student_name']
)

方法二:使用str.cat方法

利用str.cat的na_rep参数处理空值,最后去除多余空格:

df['student_id_name'] = df['student_id'].astype(str).str.cat(
    df['student_name'],
    sep=' ',
    na_rep=''
).str.strip()

方法三:使用apply逐行处理

自定义函数处理每一行的拼接逻辑:

def combine_id_name(row):
    if pd.isna(row['student_name']):
        return str(row['student_id'])
    return f"{row['student_id']} {row['student_name']}"

df['student_id_name'] = df.apply(combine_id_name, axis=1)

执行任意一种方法后,student_id_name列的结果都会符合预期:['71', '63 Peter Andrews', '23 Amy Powers']

内容的提问来源于stack exchange,提问作者Beginner in the house

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:50:28