如何将数据框堆叠在一起(Pandas,Python3)

13

假设我有三个Pandas数据框,其中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

现在,我已经将它们连接在一起,以使其成为一个DF中的6列。这很好,但是我想知道,是否有一种pandas函数可以将它们垂直堆叠到两列中并更改表头?

所以要做出像这样的东西吗?

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

我正在阅读的所有内容http://pandas.pydata.org/pandas-docs/stable/merging.html似乎只有“水平”方法用于连接数据框!

1个回答

23
只要您重命名列,使每个数据框中的列相同,pd.concat() 就可以正常工作:
# 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接