Home > Enterprise >  pandas dataframe vertical join
pandas dataframe vertical join

Time:12-01

Help me plz. I have two dataframes, for example:

| 1 | 4 | 
| 2 | 5 |
| 3 | 6 |

and

| 7 | 10 |
| 8 | 11 |
| 9 | 12 |

How to join them into one vertical dataframe like this:

| 1 | 4 | 
| 2 | 5 |
| 3 | 6 |
| 7 | 10 |
| 8 | 11 |
| 9 | 12 |

many thx

CodePudding user response:

If your goal is to vertically stack two (or more) DataFrames, independently of the indices, use numpy.vstack:

import numpy as np

out = pd.DataFrame(np.vstack(table[:2]),
                   columns=table[0].columns # optional
                  )

Output:

   0   1
0  1   4
1  2   5
2  3   6
3  7  10
4  8  11
5  9  12

CodePudding user response:

there is problem duplicated columns names, need rename them first:

print (table[0])
   col  col
0    1    4
1    2    5
2    3    6

print (table[1])
   col  col
0    7   10
1    8   11
2    9   12

#https://stackoverflow.com/a/46332739/2901002
class renamer():
    def __init__(self):
         self.d = dict()

    def __call__(self, x):
         if x not in self.d:
             self.d[x] = 0
             return x
         else:
             self.d[x]  = 1
             return "%s_%d" % (x, self.d[x])

df = pd.concat((table[0].rename(columns=renamer()), table[1].rename(columns=renamer())),
                ignore_index=True)

print (df)
   col  col_1
0    1      4
1    2      5
2    3      6
3    7     10
4    8     11
5    9     12
  • Related