programing

팬더: 엑셀 파일 시트 목록 보기

sourcejob 2022. 9. 19. 23:33
반응형

팬더: 엑셀 파일 시트 목록 보기

새로운 버전의 Panda는 다음 인터페이스를 사용하여 Excel 파일을 로드합니다.

read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])

하지만 이용 가능한 시트를 모르면 어떻게 하죠?

예를 들어, 나는 아래 시트에 있는 엑셀 파일로 작업하고 있다.

데이터 1, 데이터 2 ..., 데이터 N, foo, 바

잘 모르겠어요.N선험자

팬더에 있는 엑셀 서류에서 시트 리스트를 얻을 수 있는 방법이 있나요?

Excel File 클래스(및sheet_names★★★★★

xl = pd.ExcelFile('foo.xls')

xl.sheet_names  # see all sheet names

xl.parse(sheet_name)  # read a specific sheet to DataFrame

자세한 옵션에 대해서는, 문서를 참조해 주세요.

두 번째 매개 변수(시트 이름)를 없음으로 명시적으로 지정해야 합니다.다음과 같습니다.

 df = pandas.read_excel("/yourPath/FileName.xlsx", None);

"df"는 모두 DataFrames 사전의 시트입니다. 다음을 수행하여 확인할 수 있습니다.

df.keys()

결과는 다음과 같습니다.

[u'201610', u'201601', u'201701', u'201702', u'201703', u'201704', u'201705', u'201706', u'201612', u'fund', u'201603', u'201602', u'201605', u'201607', u'201606', u'201608', u'201512', u'201611', u'201604']

상세한 것에 대하여는, 판다의 문서를 참조해 주세요.https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html

@divingTobi의 대답에서 영감을 얻어 찾은 가장 빠른 방법입니다.xlrd, openpyxl 또는 panda에 기반한 모든 답변은 파일 전체를 먼저 로드하기 때문에 느립니다.

from zipfile import ZipFile
from bs4 import BeautifulSoup  # you also need to install "lxml" for the XML parser

with ZipFile(file) as zipped_file:
    summary = zipped_file.open(r'xl/workbook.xml').read()
soup = BeautifulSoup(summary, "xml")
sheets = [sheet.get("name") for sheet in soup.find_all("sheet")]

excel(xls., xlsx)에서 시트명을 취득하는 가장 쉬운 방법은 다음과 같습니다.

tabs = pd.ExcelFile("path").sheet_names 
print(tabs)

그런 다음 특정 시트(시트 이름은 "Sheet1", "Sheet2" 등)의 데이터를 읽고 저장하려면 예를 들어 "Sheet2"라고 입력합니다.

data = pd.read_excel("path", "Sheet2") 
print(data)
#It will work for Both '.xls' and '.xlsx' by using pandas

import pandas as pd
excel_Sheet_names = (pd.ExcelFile(excelFilePath)).sheet_names

#for '.xlsx' use only  openpyxl

from openpyxl import load_workbook
excel_Sheet_names = (load_workbook(excelFilePath, read_only=True)).sheet_names
                                      

xlrd, panda, openpyxl 등의 라이브러리를 사용해 봤는데 파일 크기가 커지면서 파일 전체를 읽을 수 있는 시간이 기하급수적으로 걸리는 것 같습니다.위에서 언급한 'on_demand'를 사용한 다른 솔루션은 나에게 효과가 없었습니다.처음에 시트 이름만 가져오려는 경우 xlsx 파일에 대해 다음 기능이 작동합니다.

def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['@sheetId'],
                'name': sheet['@name']
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets

모든 xlsx는 기본적으로 압축된 파일이기 때문에 기본 xml 데이터를 추출하고 워크북에서 직접 시트 이름을 읽습니다.이것은 라이브러리 함수에 비해 몇 초밖에 걸리지 않습니다.

매 ( : ( 4 6 66 mb xlsx )
팬더, xl: 12초
openpyxl : 24초
권장 방법: 0.4초

시트명만 읽으면 되기 때문에 계속 읽어야 하는 불필요한 오버헤드가 귀찮아서 대신 이 루트를 이용하게 되었습니다.

@dhwanil_nowledge @dhwanil_nowledge 。★★★★★★★★★★★★★★★★ zf.open압축된 파일에서 직접 읽을 수 있습니다.

import xml.etree.ElementTree as ET
import zipfile

def xlsxSheets(f):
    zf = zipfile.ZipFile(f)

    f = zf.open(r'xl/workbook.xml')

    l = f.readline()
    l = f.readline()
    root = ET.fromstring(l)
    sheets=[]
    for c in root.findall('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheets/*'):
        sheets.append(c.attrib['name'])
    return sheets

두 번 연속해서readline는 못생겼지만 내용은 텍스트의 두 번째 줄에만 있습니다.파일 전체를 해석할 필요는 없습니다.

이 해결방법은 기존 시스템보다 훨씬 빠른 것으로 보입니다.read_excel전체 추출 버전보다 빠를 수 있습니다.

from openpyxl import load_workbook

sheets = load_workbook(excel_file, read_only=True).sheetnames

5MB 엑셀 파일이라면load_workbook를 제외하고read_only플래그가 8.24초 걸렸어요를 사용하여read_only39.6밀리초밖에 걸리지 않았습니다.Excel 라이브러리를 사용하여 xml 솔루션을 사용하지 않으려면 파일 전체를 구문 분석하는 방법보다 훨씬 빠릅니다.

다음과 같은 경우:

  • 퍼포먼스에 신경을 쓰다
  • 실행 시 파일 내의 데이터는 필요 없습니다.
  • 기존의 라이브러리를 채용하고 싶다vs 독자적인 솔루션을 도입하고 싶다

아래는 최대 10MB에 대한 벤치마크입니다.xlsx,xlsb파일.

xlsx, xls

from openpyxl import load_workbook

def get_sheetnames_xlsx(filepath):
    wb = load_workbook(filepath, read_only=True, keep_links=False)
    return wb.sheetnames

벤치마크: 최대 14배의 속도 향상

# get_sheetnames_xlsx vs pd.read_excel
225 ms ± 6.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.25 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

xlsb

from pyxlsb import open_workbook

def get_sheetnames_xlsb(filepath):
  with open_workbook(filepath) as wb:
     return wb.sheets

벤치마크: 최대 56배의 속도 향상

# get_sheetnames_xlsb vs pd.read_excel
96.4 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5.36 s ± 162 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

주의:

  • 이것은 좋은 자원입니다.http://www.python-excel.org/
  • xlrd2020년을 기점으로 더 이상 유지되지 않습니다.
  1. load_workbook read only 옵션을 사용하면 몇 초 동안 눈에 띄게 대기하고 있는 실행으로 간주되었던 것이 밀리초 단위로 발생합니다.그러나 해결책은 여전히 개선될 수 있다.

     import pandas as pd
     from openpyxl import load_workbook
     class ExcelFile:
    
         def __init__(self, **kwargs):
             ........
             .....
             self._SheetNames = list(load_workbook(self._name,read_only=True,keep_links=False).sheetnames)
    
  2. Excelfile.parse는 xls 전체를 10초 단위로 읽는 것과 같은 시간이 걸립니다.이 결과는 다음 패키지 버전의 Windows 10 운영 체제에서 얻을 수 있습니다.

     C:\>python -V
     Python 3.9.1
    
     C:\>pip list
     Package         Version
     --------------- -------
     et-xmlfile      1.0.1
     numpy           1.20.2
     openpyxl        3.0.7
     pandas          1.2.3
     pip             21.0.1
     python-dateutil 2.8.1
     pytz            2021.1
     pyxlsb          1.0.8
     setuptools      49.2.1
     six             1.15.0
     xlrd            2.0.1
    

엑셀 파일을 읽으면

dfs = pd.ExcelFile('file')

그 후

dfs.sheet_names
dfs.parse('sheetname')

다른 변종

df = pd.read_excel('file', sheet_name='sheetname')

언급URL : https://stackoverflow.com/questions/17977540/pandas-looking-up-the-list-of-sheets-in-an-excel-file

반응형