[英]Read Excel with multiple headers and unnamed column
我收到一些像這樣的Excel文件:
USA UK
plane cars plane cars
2016 2 7 1 3 # a comment after the last country
2017 3 1 8 4
國家數量不明,最后一列后可以有評論。
當我這樣閱讀Excel文件時...
df = pd.read_excel(
sourceFilePath,
sheet_name = 'Sheet1',
index_col = [0],
header = [0, 1]
)
...我有一個值錯誤:
ValueError: Length of new names must be 1, got 2
問題是我無法使用usecols參數,因為在讀取文件之前我不知道有多少個國家。
我如何讀取這樣的文件?
熊貓可能無法修復您的特殊用例,但是您可以編寫一個程序來使用openpyxl修復電子表格。 它確實有清晰的文檔,但是這里是如何使用它的概述:
import openpyxl as xl
wb = xl.load_workbook("ExampleSheet.xlsx")
for sheet in wb.worksheets:
print("Sheet Title => {}".format(sheet.title))
print("Dimensions => {}".format(sheet.dimensions)) # just returns a string
print("Columns: {} <-> {}".format(sheet.min_column, sheet.max_column))
print("Rows: {} <-> {}".format(sheet.min_row, sheet.max_row))
for r in range(sheet.min_row, sheet.max_row + 1):
for c in range(sheet.min_column, sheet.max_column + 1):
if (sheet.cell(r,c).value != None):
print("Cell {}:{} has value {}".format(r,c,sheet.cell(r,c).value))
只使用pd.read_csv
怎么pd.read_csv
?
加載后,您可以使用df.columns
確定您有多少列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.