将任意数量的列中的值合并为新的值 [英] Combine values from arbitrary number of columns into new one

查看:50
本文介绍了将任意数量的列中的值合并为新的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 DataFrame 包含多列,其中每一行具有唯一值:

I have DataFrame that contains multiple columns with unique value in one of them for each row:

               A            B            C         D          E
0            NaN          NaN          NaN       NaN   POSITIVE  
1            NaN          NaN          NaN       NaN        NaN   
2            NaN          NaN          NaN       NaN   POSITIVE  
3            NaN          NaN          NaN       NaN   POSITIVE   
4       POSITIVE          NaN          NaN       NaN        NaN   
5            NaN          NaN          NaN       NaN   POSITIVE  
6            NaN          NaN          NaN       NaN   POSITIVE  
7       NEGATIVE          NaN          NaN       NaN        NaN

我需要将这些合并为一个汇总列:

I need to combine these into one summary column:

0     POSITIVE
1          NaN
2     POSITIVE
3     POSITIVE
4     POSITIVE
5     POSITIVE
6     POSITIVE
7     NEGATIVE

我使用链式 combine_first 方法完成此操作:

I accomplished this using chained combine_first method:

df.A.combine_first(df.B).combine_first(df.С).combine_first(df.В).combine_first(df.E)

后来我找到了类似的解决方案 使用 fillna:

And later I found similar solution using fillna:

df.A.fillna(df.B).fillna(df.С).fillna(df.В).fillna(df.E)

但我正在寻找对任意数量列的概括.我尝试将这些方法用作归约函数,但无法使其工作.

But I'm looking for generalization for arbitrary number of columns. I tried to apply these methods as reduction function, but couldn't make it work.

有没有关于更优雅/更有效的方法来做到这一点的想法?

Any ideas on more elegant/efficient way to do this?

推荐答案

这是我的诀窍:

df.fillna('').sum(axis=1).replace('', np.nan)

这篇关于将任意数量的列中的值合并为新的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆