7

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

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
piRSquared
  • 285,575
  • 57
  • 475
  • 624
viper
  • 71
  • 1
  • 3

1 Answers1

9

Option 1

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

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

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

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

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
piRSquared
  • 285,575
  • 57
  • 475
  • 624