每个 Excel 工作表上都有 3 个表格:sheet1 - 毛额
、sheet2 - 利润
、sheet3 - 收入
因此我能够迭代每个工作表并将其逆透视。
但是我怎样才能将它们结合在一起呢?
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)
期望的结果:
更新:
谢谢@Celius Stingher。 我想这就是我所需要的。它只是给了我奇怪的排序:
并给我这个警告:
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/