如何使用python在循环中连接多个数据帧

2024-06-02 07:05:03 发布

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

每个excel工作表上有3个表:sheet1-Gross、sheet2-Margin、sheet3-Revenue

因此,我能够遍历每个工作表并将其解压

但是我怎样才能把它们结合在一起呢

enter image description here

    sheet_names = ['Gross','Margin','Revenue']

    full_table = pd.DataFrame()
    for sheet in sheet_names:
        df = pd.read_excel(BudgetData.xlsx', sheet_name = sheet, index=False)
        unpvt = pd.melt(df,id_vars=['Company'], var_name ='Month', value_name = sheet)
# how can I join unpivoted dataframes here?
        print(unpvt)

enter image description here

理想结果:

enter image description here

更新:

谢谢@Celius Stingher。 我想这就是我需要的。这让我觉得很奇怪:

enter image description here

并警告我:

Sorting because non-concatenation axis is not aligned. A future version
of pandas will change to not sort by default.

To accept the future behavior, pass 'sort=False'.

To retain the current behavior and silence the warning, pass 'sort=True'.

  from ipykernel import kernelapp as app

Tags: thenamemarginfalsedfnamesnotfuture
2条回答

一个pd.concat将把所有的东西都堆在一起,您需要使用pd.merge实际合并数据帧。这类似于SQL Join语句。(基于您帖子中的“期望”图片)

https://pandas.pydata.org/pandas-docs/version/0.19.1/generated/pandas.DataFrame.merge.html

您只需要使用要合并的列列表。如果将它们全部放入与工作表同名的整齐数据框中,则需要执行以下操作:

gross.merge(margin, on=['Company', 'Month']).merge(revenue, on=['Company', 'Month'])

因此,您似乎正在进行数据透视,但没有将每个未插入的数据帧保存到任何位置。让我们创建一个数据帧列表,它将存储每个未插入的数据帧。稍后,我们将把数据帧列表作为参数传递给pd.concat函数以执行连接

sheet_names = ['Gross','Margin','Revenue']
list_of_df = []
full_table = pd.DataFrame()
for sheet in sheet_names:
    df = pd.read_excel(BudgetData.xlsx', sheet_name = sheet, index=False)
    df = pd.melt(df,id_vars=['Company'], var_name ='Month', value_name = sheet)
    list_of_df.append(df)

full_df = pd.concat(list_of_df,ignore_index=True)
full_df = full_df.sort_values(['Company','Month'])
print(full_df)

编辑:

现在我了解了您的需要,让我们尝试一种不同的方法。在循环之后,尝试以下代码来读取pd.concat

full_df = list_of_df[0].merge(list_of_df[1],on=['Company','Month']).merge(list_of_df[2],on=['Company','Month'])

相关问题 更多 >