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

如何基于NaN条件在Pandas DataFrame中新增列?

问题描述

我有两个DataFrame,需要判断df1中player列的单元格是否存在于df2的last_name列中。已经通过左连接合并得到df3:

df3 = df1.merge(df2, left_on='player', right_on='last_name', how='left')

df1数据:

player球队位置
Tatum凯尔特人队SF
Brown凯尔特人队SG
Smart凯尔特人队PG
Horford凯尔特人队C
Brogdon凯尔特人队PG
Gallinari凯尔特人队F

df2数据:

last_name球队位置
Durant篮网队SF
James湖人队SF
Smart凯尔特人队PG
Horford凯尔特人队C
Davis湖人队C
Curry勇士队PG

之后将last_name列重命名为matched_player:

df3.rename(columns={'last_name':'matched_player'}, inplace=True)

合并后的df3如下:

player球队位置matched_player
Tatum凯尔特人队SFNaN
Brown凯尔特人队SGNaN
Smart凯尔特人队PGSmart
Horford凯尔特人队CHorford
Brogdon凯尔特人队PGNaN
Gallinari凯尔特人队FNaN

我需要新增description列,当matched_player列不为NaN时,该列值为"来自df1的球员",其余行留空,预期输出如下:

player球队位置matched_playerdescription
Tatum凯尔特人队SFNaN
Brown凯尔特人队SGNaN
Smart凯尔特人队PGSmart来自df1的球员
Horford凯尔特人队CHorford来自df1的球员
Brogdon凯尔特人队PGNaN
Gallinari凯尔特人队FNaN

请问该如何实现?

解决方案

这里有几种简单直接的方法可以实现需求:

方法1:用numpy.where做条件赋值

借助numpy.where可以一行完成条件判断和赋值:

import numpy as np

df3['description'] = np.where(df3['matched_player'].notna(), '来自df1的球员', '')

方法2:用pandas.loc定位赋值

先初始化description列为空字符串,再定位matched_player非空的行赋值:

df3['description'] = ''
df3.loc[df3['matched_player'].notna(), 'description'] = '来自df1的球员'

方法3:用Series.where反向赋值

先给所有行设置描述文本,再把matched_player为空的行替换成空字符串:

df3['description'] = '来自df1的球员'
df3['description'] = df3['description'].where(df3['matched_player'].notna(), '')

以上三种方法都能得到你想要的预期结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:24:20