0

kind of new to pandas.

I have

df1 = pd.Dataframe(
    [
    {'a': 1},
    {'a': 2},
    {'a': 3},
    ]
)

df2 = pd.Dataframe(
    [
    {'a': 4},
    {'a': 5},
    ]
)

I want

 df_id  a
 1      1
        2
        3
 2      4
        5
        

Assume I have a list of dfs like df1 and df2. What is the correct way to get the result df?

Am I supposed to also declare some column as a key? or a primary key? Notice that I want to retain the option to slice this dataframe by df_id to get back the original dfs.

Also, what is this operation called? I didn't even know what to search for.

Gulzar
  • 10,451
  • 10
  • 52
  • 87
  • Use `pd.concat([df1, df2])`. – Henry Yik Oct 25 '20 at 14:41
  • 2
    This [this fantastic answer](https://stackoverflow.com/questions/53645882/pandas-merging-101) is a great resource for those times when you're trying to merge dfs – cfort Oct 25 '20 at 14:50

1 Answers1

3

pd.concat([df1, df2], keys=[1,2]) if you want to keep everything for later re-use:

     a
1 0  1
  1  2
  2  3
2 0  4
  1  5

or if you want to drop the original indexes:

pd.concat([df1, df2], keys=[1,2]).droplevel(1)

   a
1  1
1  2
1  3
2  4
2  5
cfort
  • 2,081
  • 1
  • 15
  • 22