programing

Excel 명명된 범위를 팬더 데이터 프레임으로 읽기

sourcejob 2023. 9. 21. 20:16
반응형

Excel 명명된 범위를 팬더 데이터 프레임으로 읽기

Excel의 지정된 범위에서 팬더 DataFrame으로 데이터를 읽을 수 있는 방법은 무엇입니까?

안타깝게도, 표준 함수는pandas.read_excel()워크북 내의 전체 시트만 읽을 수 있도록 설계되었습니다.

아마도 언젠가 판다들이 자연스럽게 이를 지지할 것입니다.그때까지는 도우미 기능을 사용합니다.

import pandas as pd
import openpyxl

def data_frame_from_xlsx(xlsx_file, range_name):
    """ Get a single rectangular region from the specified file.
    range_name can be a standard Excel reference ('Sheet1!A2:B7') or 
    refer to a named region ('my_cells')."""
    wb = openpyxl.load_workbook(xlsx_file, data_only=True, read_only=True)
    if '!' in range_name:
        # passed a worksheet!cell reference
        ws_name, reg = range_name.split('!')
        if ws_name.startswith("'") and ws_name.endswith("'"):
            # optionally strip single quotes around sheet name
            ws_name = ws_name[1:-1]
        region = wb[ws_name][reg]
    else:
        # passed a named range; find the cells in the workbook
        full_range = wb.get_named_range(range_name)
        if full_range is None:
            raise ValueError(
                'Range "{}" not found in workbook "{}".'.format(range_name, xlsx_file)
            )
        # convert to list (openpyxl 2.3 returns a list but 2.4+ returns a generator)
        destinations = list(full_range.destinations) 
        if len(destinations) > 1:
            raise ValueError(
                'Range "{}" in workbook "{}" contains more than one region.'
                .format(range_name, xlsx_file)
            )
        ws, reg = destinations[0]
        # convert to worksheet object (openpyxl 2.3 returns a worksheet object 
        # but 2.4+ returns the name of a worksheet)
        if isinstance(ws, str):
            ws = wb[ws]
        region = ws[reg]
    # an anonymous user suggested this to catch a single-cell range (untested):
    # if not isinstance(region, 'tuple'): df = pd.DataFrame(region.value)
    df = pd.DataFrame([cell.value for cell in row] for row in region)
    return df

Microsoft Office 도움말 페이지 인용하기!

[이름이 붙은 범위]는 일견 이해하기 어려울 수 있는 셀 참조, 상수, 공식 또는 표의 목적을 쉽게 이해할 수 있게 해주는 의미 있는 축약어입니다."

명명된 범위는 ODBC를 통해 데이터에 쉽게 액세스할 수 있도록 스프레드시트에서 더 자주 사용되며, 동일한 워크시트 내에 여러 개의 데이터 범위가 있을 때 특히 유용합니다.ODBC를 통해 Excel에 연결하려면 적절한 Excel 드라이버를 선택하고 다음과 같은 SQL 문을 전송하기만 하면 됩니다.

SELECT * 
FROM namedRange

Pandas에서 유용한 명령어는 read_sql일 수 있습니다.

그러나 윈도우즈의 경우 이 솔루션을 사용하려면 설치된 Excel 소프트웨어 버전(32비트 또는 64비트), ODBC 드라이버 및 ODBC 연결을 여는 소프트웨어 패키지를 정렬/스트리밍해야 합니다.예를 들어 설치된 Excel 32비트 버전의 경우 32비트 ODBC 드라이버와 일반적으로 32비트 Python을 설치해야 합니다.참고: Python 사례(Python 초보자입니다)에 대해서는 나중에 확인해야 하지만 SAS, SPSS 또는 Stata에서 시작한 ODBC 연결에 대해서는 확실히 확인할 수 있습니다.

이전 요구사항은 매우 중대한 단점이며 실제로 ODBC를 전혀 포함하지 않는 모든 솔루션에 찬성합니다.그렇기는 하지만 읽어보면 좋을 것 같습니다.엑셀은 그런 시설을 제공했습니다.이러한 맥락에서 SAS, SPSS 및 Stata는 현재 각각의 Excel 필터에서 명명된 범위에 직접 액세스할 수 없습니다. 따라서 이러한 기능이 부족한 데에는 객관적인 이유가 있을 수 있습니다.

openpyxl을 사용하여 []의 범위를 복사하는 방법은 다음과 같습니다.

wb = load_workbook(filename=xlPath)
ws, range= next(wb.defined_names["rangename"].destinations)
materials = [[cell.value for cell in row] for row in wb[ws][range]]

기본적으로 사용할 수 있습니다.xlrd이거 포장.

xlrd포장은 함께 나옵니다.examples다음을 xlrdnameAPIdemo.py, 여기에 기록된 바와 같이

간단히 말해서, 이름이 붙은 범위를 가리킵니다.print_area도:

book = xlrd.open_workbook('examples/namesdemo.xls')
name_obj = book.name_map['print_area'][0]
print name_obj.__dict__

봐요.name_obj항목이 있습니다.

'result': Operand(kind=oREF, value=[Ref3D(coords=(2, 3, 0, 4, 0, 14))], text=u'Sheet3!$A$1:$N$4')

할 수 값 일 수도 않을 수도 . , .result.kind.

하여 Mac에서 의 스프레드시트를 하면 하여(Mac 에서된) 에서된이 result이었다None에, 유일한 는 에, 의 를 나타냅니다.name_obj다음과 같음:

'formula_text': u'Sheet1!$B$6:$E$11'

그래서 일반적인 경우에 이것을 할 수 있는 방법이 있을 수 있지만 시행착오가 좀 걸릴 것 같습니다.

이 지정된 뒤에 할 수 ()key빈 변수를 . ), 하며, .pd.read_excel:

def table_position(path, sheet_name, key):
    """
    Find the start and end rows of a table in an Excel spreadsheet
    based on the first occurence of key text on the sheet, and down
    to the first blank line.

    Returns (col, start_row, end_row, skip_footer)

    where: 
        col is the column number containing the key text,
        start_row is the row after this, 
        end_row is the row number of the next blank line,
        skip_footer is how many rows from the end of the sheet this is.

    You can then read in the table with:
        x = pd.read_excel(path, sheet_name, skiprows=start, skip_footer=skip_footer, header=0)
        x = x.dropna(axis=1, how='all')
    """
    import xlrd
    book = xlrd.open_workbook(path)
    sheet = book.sheet_by_name(sheet_name)
    # find the first occurrence of the key, and the next line break
    (col, start, end) = (-1, -1, sheet.nrows)
    for rownum in xrange(sheet.nrows):
        if col<0: # look for key to start the table off
            try:
                test_col = next(c for c in xrange(sheet.ncols) if sheet.cell(rownum, c).value==key)
            except StopIteration:
                pass
            else:
                col, start = test_col, rownum+1 # row after key text is the start
        else: # test for blank line as end of table
            if not [True for cell in sheet.row(rownum) if cell.value]:
                end = rownum
                break
    skip_footer = sheet.nrows - end
    return (col, start, end, skip_footer)

,pd.read_excel그러면 데이터 파일을 두 번 읽게 되는데, 그건 어리석은 일이지만, 아이디어는 알 수 있습니다.

글쎄요, 오랜만이지만 xlwings에게 주사를 놓는 것을 꼭 추천합니다.

Xlwings는 정의된 이름에서 값을 가져옵니다.

read_excel을 사용하면 다음과 같은 기능을 제공합니다.

skiprows : list-like
    Rows to skip at the beginning (0-indexed)

skip_footer : int, default 0
    Rows at the end to skip (0-indexed)

parse_cols : int or list, default None
        If None then parse all columns,
        If int then indicates last column to be parsed
        If list of ints then indicates list of column numbers to be parsed
        If string then indicates comma separated list of column names and column ranges (e.g. “A:E” or “A,C,E:F”)

즉, 열 이름과 행 번호("이름 있는 범위"를 알고 있다면 해당 섹션만 선택하여 DataFrame을 만들 수 있습니다.

언급URL : https://stackoverflow.com/questions/20486453/reading-an-excel-named-range-into-a-pandas-dataframe

반응형