[英]Merging two DataFrame columns
我有 3 個包含不同列的 excel 文件要合並我使用此代碼是為了嘗試僅合並其中的 2 個
one = pd.read_excel("output3.xlsx")
two = pd.read_excel("output2.xlsx")
one = one.join(two)
但這不會為我合並列,並給我一個錯誤:
ValueError: 列重疊但未指定后綴:Index(['Unnamed: 0', 'Unnamed: 1', 'Unnamed: 2', 'Unnamed: 3'], dtype='object')
網上搜了一下,找到了concat函數和left join和right join函數,但是沒有共同的列。
我只想將 3 個 Excel 連接成 1 個,每個都使用 Pandas 進入其常規位置。
我的 Excel 表格看起來像這樣
問題是您的所有列都未命名,您可以執行以下操作:
one = pd.read_excel("output3.xlsx")
two = pd.read_excel("output2.xlsx")
# give nice, different names to your columns
one.columns = ['col_1', 'col_2', 'col_3', 'col_4']
two.columns = ['col_5', 'col_6', 'col_7', 'col_8']
one = one.join(two)
這實際上可能是一個串聯應用程序,而不是連接應用程序:
df1 = pd.DataFrame([[1,2,3]]*5)
df2 = pd.DataFrame([[None,None,None,4,5,6]]*5, index = range(5))
df3 = pd.concat([df1,df2],axis=1).dropna(axis=1)
如果您知道表具有相同的行數,則 concat 會更容易。 axis = 1 表示垂直串聯。 dropna 方法將刪除沒有值的列。
這個問題用pandas
標記,並提到您已經嘗試過 DataFrames,但鑒於您試圖通過填充行和列的范圍來組合這些電子表格,我建議您使用openpyxl
(如果您使用的是 2010+ .xlsx 文件) 或xlrd/xlwt
(如果您使用的是較舊的 .xls 文件)。
此腳本假定您知道每個工作簿中的行數/列數,並且每個單元格塊都將在最終 Excel 電子表格中完全相同的位置結束。 (這些也可以通過更多的工作以編程方式確定,但要保持簡單的開始。)為每個工作簿的行和列設置開始/停止值,例如:
# Set workbook 1 column and row start/stop values
# indexed by 1
wb1_col = [5, 8]
wb1_row = [2, 13]
# Do same for sheet 2 and sheet 3
wb2_col = [1, 4]
wb2_row = [2, 13]
wb3_col = [1, 8]
wb3_row = [1, 2]
現在您可以提取這些范圍內的單元格並將它們插入到新的電子表格中:
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
from openpyxl import Workbook
# Open existing spreadsheet/worksheet (modify name of worksheet to match yours)
wb1 = load_workbook(filename='output1.xlsx')['Sheet 1']
wb2 = load_workbook(filename='output2.xlsx')['Sheet 1']
wb3 = load_workbook(filename='output3.xlsx')['Sheet 1']
# Open a new spreadsheet/worksheet
wb = Workbook()
ws = wb.active
# Put data from workbook 1 into the new workbook
for column in range(wb1_col[0], wb1_col[1]):
column_letter = get_column_letter(column)
for row in range(wb1_row[0], wb1_row[1]):
coordinates = column_letter + str(row)
ws[coordinates] = wb1[coordinates]
# Put data from workbook 2 into the new workbook
for column in range(wb2_col[0], wb2_col[1]):
column_letter = get_column_letter(column)
for row in range(wb2_row[0], wb2_row[1]):
coordinates = column_letter + str(row)
ws[coordinates] = wb2[coordinates]
# Put data from workbook 3 into the new workbook
for column in range(wb3_col[0], wb3_col[1]):
column_letter = get_column_letter(column)
for row in range(wb3_row[0], wb3_row[1]):
coordinates = column_letter + str(row)
ws[coordinates] = wb3[coordinates]
# Write the results to a file
wb.save("new.xlsx")
現在新工作表被稱為new.xlsx
並在其相應的單元格位置包含所有 3 個工作表的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.