[英]How to join multiple dataframes within a loop using python pandas
我在每個 excel 表上有 3 個表: sheet1 - Gross
, sheet2 - Margin
, sheet3 - Revenue
所以我能夠遍歷每個工作表並取消旋轉它。
但是我怎樣才能把它們結合在一起呢?
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 中pd.concat
以下代碼:
full_df = list_of_df[0].merge(list_of_df[1],on=['Company','Month']).merge(list_of_df[2],on=['Company','Month'])
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'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.