【问题标题】:How to Stack Data Frames on top of one another (Pandas,Python3)如何将数据帧堆叠在一起(Pandas,Python3)
【发布时间】:2014-11-25 19:51:19
【问题描述】:

假设我有 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 函数可以将它们垂直堆叠成两列并更改标题?

所以要制作这样的东西?

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 的方法!

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-28
      • 2015-02-15
      • 2012-10-16
      • 2020-03-09
      • 2022-12-21
      • 2017-04-20
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多