在pandas中将两个数据框列合并为1 [英] merge two dataframe columns into 1 in pandas

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

问题描述

我的数据框中有2列,我需要将其合并为1个单列

I have 2 columns in my data frame and I need to merge it into 1 single column

Index  A             Index   B
0      A             0       NAN
1      NAN           1       D
2      B             2       NAN
3      NAN           3       E
4      C             4       NAN

在列中始终有一个1值,我希望我的结果看起来像

there will always be one 1 value across the Columns, i want my result to look like

0    A
1    B
2    C
3    D
4    E

推荐答案

选项1

Option 1

df.stack().dropna().reset_index(drop=True)

0    A
1    D
2    B
3    E
4    C
dtype: object

选项2 如果缺失值总是交替出现的

Option 2 If Missing values are always alternating

df.A.combine_first(df.B)

Index
0    A
1    D
2    B
3    E
4    C
Name: A, dtype: object

选项3 您要什么

Option 3 What you asked for

df.A.append(df.B).dropna().reset_index(drop=True)

0    A
1    B
2    C
3    D
4    E
dtype: object

选项4 类似于3,但超过任意列数

Option 4 Similar to 3 but over arbitrary number of columns

pd.concat([i for _, i in df.iteritems()]).dropna().reset_index(drop=True)

0    A
1    B
2    C
3    D
4    E
dtype: object

这篇关于在pandas中将两个数据框列合并为1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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