python - 优先合并 2 列

标签 python pandas merge

我有一个包含 2 列 A 和 B 的 pandas df。我需要的是一个新的合并列“结果”,其中 A 优于 B。我真的认为这很容易,但仍然没有解决方案。你们会怎么做?感谢您的帮助。

A   B   result
go  for go
go      go
go      go
    for for
    for for

最佳答案

使用combine_firstfillna :

df['result'] = df['A'].combine_first(df['B'])
print (df)
     A    B result
0   go  for     go
1   go  NaN     go
2   go  NaN     go
3  NaN  for    for
4  NaN  for    for

或者:

df['result'] = df['A'].fillna(df['B'])
print (df)
     A    B result
0   go  for     go
1   go  NaN     go
2   go  NaN     go
3  NaN  for    for
4  NaN  for    for

编辑:

要将空格替换为 NaN,请使用:

df = df.replace('', np.nan)

或者:

df = df.mask(df == '')

关于python - 优先合并 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46807354/

相关文章:

Python float 除以零错误

python - 如何将参数化的sql查询放入变量然后在Python中执行?

python - 在Python子进程中运行call()时出错

python - 水平堆积条形图并为每个部分添加标签

c# - 使用C#重叠和合并2个WAV文件

python - 如何在 Scrapy 中 'pause' 蜘蛛?

python - 旋转 Pandas 数据框以查看是否满足条件

list - 在 Pandas Dataframe 中查找空或 NaN 条目

git 所有标记为冲突的文件

c++ - 使用 stringstream 从循环中的另一个字符串构建字符串