如何基于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 | 凯尔特人队 | SF | NaN |
| Brown | 凯尔特人队 | SG | NaN |
| Smart | 凯尔特人队 | PG | Smart |
| Horford | 凯尔特人队 | C | Horford |
| Brogdon | 凯尔特人队 | PG | NaN |
| Gallinari | 凯尔特人队 | F | NaN |
我需要新增description列,当matched_player列不为NaN时,该列值为"来自df1的球员",其余行留空,预期输出如下:
| player | 球队 | 位置 | matched_player | description |
|---|---|---|---|---|
| Tatum | 凯尔特人队 | SF | NaN | |
| Brown | 凯尔特人队 | SG | NaN | |
| Smart | 凯尔特人队 | PG | Smart | 来自df1的球员 |
| Horford | 凯尔特人队 | C | Horford | 来自df1的球员 |
| Brogdon | 凯尔特人队 | PG | NaN | |
| Gallinari | 凯尔特人队 | F | NaN |
请问该如何实现?
解决方案
这里有几种简单直接的方法可以实现需求:
方法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
相关产品推荐
相关产品推荐

