![](/img/trans.png)
[英]How to combine 5 Excel files with the same name but in 5 different folders?
[英]How combine two excel files with the same columns name same format, only dates are different, and the column order should base on the same column name
表 1: | 日期 | 重量| 身高 | 寬度|
12/27/2022 1 2 3
12/27/2022 4 5 6
表 2 | 日期 | 重量| 身高 | 寬度|
2023 年 1 月 3 日 1 2 3
2023 年 1 月 3 日 4 5 6
組合表應為:|date1| 日期2| 重量1| 體重2|身高1| 高度2| 寬度1| 寬度2|
任何人都可以使用 python (Pandas) 來解決這個問題嗎? 謝謝!
這應該可以解決問題,它不是最優雅的,但可以完成工作。 - 聽 Lil Wayne 的聲音!
import pandas as pd
df1 = pd.read_csv('table_1.csv', sep=' ')
df2 = pd.read_csv('table_2.csv', sep=' ')
# add file number to each column
df1.columns = [x +'_1' for x in df1.columns]
df2.columns = [x +'_2' for x in df2.columns]
# save these for later
df1_cols = df1.columns
df2_cols = df2.columns
# make the final column ordering
final_col_order = []
for one, two in zip(df1_cols, df2_cols):
final_col_order.append(one)
final_col_order.append(two)
# loop through just table 2 columns
for col in df2_cols:
# add each table 2 cols to table 1
df1[col] = df2[col]
# apply the final ordering you like, and copy it to a new df
df = df1[final_col_order].copy()
df.head()
我假設你已經將這些數據讀入 pandas 數據幀,因為你提到了它,就像 pandas read_excel 一樣。
在將表讀入 pandas dataframe 之后,看起來您只需要合並 function。
df1.merge(df2, left_on='lkey', right_on='rkey')
官方文檔在這里: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html
您的表格格式很難閱讀,但如果您只想合並它們然后更改列順序,您可以使用它在連接后重新排列它們。
根據列名更改 cols 的順序:
df.loc[:,['Column1name','column5name','column2name','column4name']]
這會讓你成功一半:
df = pd.concat([df1, df2], axis=1)
df
date weight height width date weight height width
0 12/27/2022 1 2 3 01/03/2023 1 2 3
1 12/27/2022 4 5 6 01/03/2023 4 5 6
然后您可以根據需要重新排序和重命名您的列。
# rename the columns
df.columns = ['date1', "weight1", "height1", "width1", 'date2', "weight2", "height2", "width2"]
# reorder the columns
df = df[['date1','date2', "weight1","weight2", "height1","height2", "width1", "width2"]]
df
date1 date2 weight1 weight2 height1 height2 width1 width2
0 12/27/2022 01/03/2023 1 1 2 2 3 3
1 12/27/2022 01/03/2023 4 4 5 5 6 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.