Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Stack Data Frames on top of one another (Pandas,Python3)

Lets say i Have 3 Pandas DF

DF1

 Words      Score
 The Man     2
 The Girl    4

Df2

 Words2      Score2
The Boy       6
The Mother    7

Df3

Words3       Score3
The Son        3
The Daughter   4

Right now, I have them concatenated together so that it becomes 6 columns in one DF. That's all well and good but I was wondering, is there a pandas function to stack them vertically into TWO columns and change the headers?

So to make something like this?

Family Members     Score
The Man             2
The Girl            4
The Boy             6
The Mother          7
The Son             3
The Daughter        4

everything I'm reading here http://pandas.pydata.org/pandas-docs/stable/merging.html seems to only have "horizontal" methods of joining DF!

like image 763
user3682157 Avatar asked Oct 01 '14 03:10

user3682157


People also ask

How do pandas stack DataFrames on top of each other?

Concat() function simply adds DataFrames on top of each other or adds them side-by-side. It is more like appending DataFrames. Merge() combines DataFrames based on values in shared columns.

How do you stack two data frames in Python?

When we concatenate DataFrames, we need to specify the axis. axis=0 tells pandas to stack the second DataFrame UNDER the first one. It will automatically detect whether the column names are the same and will stack accordingly. axis=1 will stack the columns in the second DataFrame to the RIGHT of the first DataFrame.

How do I merge 3 data frames in pandas?

We can use either pandas. merge() or DataFrame. merge() to merge multiple Dataframes. Merging multiple Dataframes is similar to SQL join and supports different types of join inner , left , right , outer , cross .


1 Answers

As long as you rename the columns so that they're the same in each dataframe, pd.concat() should work fine:

# I read in your data as df1, df2 and df3 using:
# df1 = pd.read_clipboard(sep='\s\s+')
# Example dataframe:

Out[8]: 
      Words  Score
0   The Man      2
1  The Girl      4


all_dfs = [df1, df2, df3]

# Give all df's common column names
for df in all_dfs:
    df.columns = ['Family_Members', 'Score']

pd.concat(all_dfs).reset_index(drop=True)

Out[16]: 
  Family_Members  Score
0        The Man      2
1       The Girl      4
2        The Boy      6
3     The Mother      7
4        The Son      3
5   The Daughter      4
like image 183
Marius Avatar answered Oct 21 '22 15:10

Marius