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

2024-04-29 03:32:12 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有三只熊猫

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!


Tags: thepandasdfscoredf1wordsboydf2
1条回答
网友
1楼 · 发布于 2024-04-29 03:32:12

只要重命名列,使其在每个数据帧中相同,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

相关问题 更多 >