python - 如何使用 python pandas 在循环中加入多个数据帧

标签 python pandas dataframe join

每个 Excel 工作表上都有 3 个表格:sheet1 - 毛额、sheet2 - 利润、sheet3 - 收入

因此我能够迭代每个工作表并将其逆透视。

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

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

最佳答案

所以看来您正在进行旋转,但没有在任何地方保存每个未旋转的数据帧。让我们创建一个数据帧列表,它将存储每个未旋转的数据帧。稍后,我们将将该数据帧列表作为 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'])

关于python - 如何使用 python pandas 在循环中加入多个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59976789/

相关文章:

python - Pandas - 从字典列表创建 df

python - 如何计算tensorflow张量中的元素?

python - pandas read_csv 删除空白行

dataframe - 如何使用 cumfold 或 cumreduce 创建有状态列

python - Pandas DataFrame.agg 在选择缺失类别后生成多重索引

python - 如何在我的代码中显示正确的单词,我的代码是 : os. urandom(64)

python - 将元组的 spark RDD 转换为 numpy 数组

python - 使用 groupby 对 Pandas DataFrame 进行计算,然后将其传回到 DataFrame 中?

python - 如何迭代 Pandas 中的列值并根据同一行中多列的值创建新的观察?

python - 有没有办法从不同长度的 Pandas 数据框中移动多行?