如何将数据帧堆叠在一起(Pandas,Python3) [英] How to Stack Data Frames on top of one another (Pandas,Python3)

查看:61
本文介绍了如何将数据帧堆叠在一起(Pandas,Python3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 3 个 Pandas DF

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

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

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

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

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

推荐答案

只要您重命名列以使它们在每个数据框中都相同,pd.concat() 应该可以正常工作:

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

这篇关于如何将数据帧堆叠在一起(Pandas,Python3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆