如何将数据帧堆叠在一起(Pandas、Python3)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26133465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:31:51  来源:igfitidea点击:

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

pythonpython-3.xpandas

提问by user3682157

Lets say i Have 3 Pandas DF

假设我有 3 个 Pandas DF

DF1

DF1

 Words      Score
 The Man     2
 The Girl    4

Df2

DF2

 Words2      Score2
The Boy       6
The Mother    7

Df3

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?

现在,我将它们连接在一起,使其成为一个 DF 中的 6 列。一切都很好,但我想知道,是否有一个 Pandas 函数可以将它们垂直堆叠成两列并更改标题?

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.htmlseems to only have "horizontal" methods of joining DF!

我在这里阅读的所有内容http://pandas.pydata.org/pandas-docs/stable/merging.html似乎只有“横向”加入 DF 的方法!

回答by Marius

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

只要您重命名列以使它们在每个数据框中都相同,就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