user3682157
user3682157

Reputation: 1695

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!

Upvotes: 13

Views: 26024

Answers (1)

Marius
Marius

Reputation: 60060

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

Upvotes: 23

Related Questions