programing

파이썬을 사용하여 엑셀 파일을 읽는 중, 표시된 열 이름을 가진 특정 열의 값을 얻으려면 어떻게 해야 합니까?

skycolor 2023. 5. 27. 09:59
반응형

파이썬을 사용하여 엑셀 파일을 읽는 중, 표시된 열 이름을 가진 특정 열의 값을 얻으려면 어떻게 해야 합니까?

Excel 파일이 있습니다.

Arm_id      DSPName        DSPCode          HubCode          PinCode    PPTL
1            JaVAS            01              AGR             282001    1,2
2            JaVAS            01              AGR             282002    3,4
3            JaVAS            01              AGR             282003    5,6

양식에 문자열을 저장합니다.Arm_id,DSPCode,Pincode이 형식은 구성할 수 있습니다. 즉, 다음으로 변경될 수 있습니다.DSPCode,Arm_id,Pincode다음과 같은 목록에 저장합니다.

FORMAT = ['Arm_id', 'DSPName', 'Pincode']

제공된 이름을 가진 특정 열의 내용을 읽는 방법은 다음과 같습니다.FORMAT구성할 수 있습니까?

이것이 제가 시도한 것입니다.현재 파일의 모든 내용을 읽을 수 있습니다.

from xlrd import open_workbook
wb = open_workbook('sample.xls')
for s in wb.sheets():
    #print 'Sheet:',s.name
    values = []
    for row in range(s.nrows):
        col_value = []
        for col in range(s.ncols):
            value  = (s.cell(row,col).value)
            try : value = str(int(value))
            except : pass
            col_value.append(value)
        values.append(col_value)
print values

내 출력은 다음과 같습니다.

[
    [u'Arm_id', u'DSPName', u'DSPCode', u'HubCode', u'PinCode', u'PPTL'],
    ['1', u'JaVAS', '1', u'AGR', '282001', u'1,2'], 
    ['2', u'JaVAS', '1', u'AGR', '282002', u'3,4'], 
    ['3', u'JaVAS', '1', u'AGR', '282003', u'5,6']
]

그리고 나는 빙글빙글 돈다.values[0]그것을 알아내려고 노력하는 것.FORMAT의 내용.values[0]그리고 나서 색인을 얻습니다.Arm_id, DSPname and Pincode에서values[0]그리고 나서 다음 루프부터 나는 모든 것의 색인을 알고 있습니다.FORMAT요소를 사용하여 어떤 값을 얻어야 하는지 알 수 있습니다.

하지만 이것은 정말 형편없는 해결책입니다.

엑셀 파일에 이름이 있는 특정 열의 값을 가져오려면 어떻게 해야 합니까?

다소 늦은 답변이지만 팬더를 사용하면 엑셀 파일의 열을 직접 얻을 수 있습니다.

import pandas

df = pandas.read_excel('sample.xls')
#print the column names
print df.columns
#get the values for a given column
values = df['Arm_id'].values
#get a data frame with selected columns
FORMAT = ['Arm_id', 'DSPName', 'Pincode']
df_selected = df[FORMAT]

xlrd 및 panda를 설치했는지 확인합니다.

pip install pandas xlrd

한 가지 접근 방식은 다음과 같습니다.

from xlrd import open_workbook

class Arm(object):
    def __init__(self, id, dsp_name, dsp_code, hub_code, pin_code, pptl):
        self.id = id
        self.dsp_name = dsp_name
        self.dsp_code = dsp_code
        self.hub_code = hub_code
        self.pin_code = pin_code
        self.pptl = pptl

    def __str__(self):
        return("Arm object:\n"
               "  Arm_id = {0}\n"
               "  DSPName = {1}\n"
               "  DSPCode = {2}\n"
               "  HubCode = {3}\n"
               "  PinCode = {4} \n"
               "  PPTL = {5}"
               .format(self.id, self.dsp_name, self.dsp_code,
                       self.hub_code, self.pin_code, self.pptl))

wb = open_workbook('sample.xls')
for sheet in wb.sheets():
    number_of_rows = sheet.nrows
    number_of_columns = sheet.ncols

    items = []

    rows = []
    for row in range(1, number_of_rows):
        values = []
        for col in range(number_of_columns):
            value  = (sheet.cell(row,col).value)
            try:
                value = str(int(value))
            except ValueError:
                pass
            finally:
                values.append(value)
        item = Arm(*values)
        items.append(item)

for item in items:
    print item
    print("Accessing one single value (eg. DSPName): {0}".format(item.dsp_name))
    print

당신은 커스텀 클래스를 사용할 필요가 없습니다, 당신은 간단히 수업을 들을 수 있습니다.dict()그러나 클래스를 사용하는 경우 위에서 보는 것처럼 점 표기법을 통해 모든 값에 액세스할 수 있습니다.

위 스크립트의 출력은 다음과 같습니다.

Arm object:
  Arm_id = 1
  DSPName = JaVAS
  DSPCode = 1
  HubCode = AGR
  PinCode = 282001 
  PPTL = 1
Accessing one single value (eg. DSPName): JaVAS

Arm object:
  Arm_id = 2
  DSPName = JaVAS
  DSPCode = 1
  HubCode = AGR
  PinCode = 282002 
  PPTL = 3
Accessing one single value (eg. DSPName): JaVAS

Arm object:
  Arm_id = 3
  DSPName = JaVAS
  DSPCode = 1
  HubCode = AGR
  PinCode = 282003 
  PPTL = 5
Accessing one single value (eg. DSPName): JaVAS

그래서 중요한 부분은 헤더를 잡는 것입니다.col_names = s.row(0)) 및 행을 반복할 때 필요 없는 첫 번째 행을 건너뜁니다.for row in range(1, s.nrows)1부터 시작하는 범위(암묵적 0이 아님)를 사용하여 수행됩니다.그런 다음 zip을 사용하여 'name'을(를) 열 머리글로 지정한 행을 단계별로 표시합니다.

from xlrd import open_workbook

wb = open_workbook('Book2.xls')
values = []
for s in wb.sheets():
    #print 'Sheet:',s.name
    for row in range(1, s.nrows):
        col_names = s.row(0)
        col_value = []
        for name, col in zip(col_names, range(s.ncols)):
            value  = (s.cell(row,col).value)
            try : value = str(int(value))
            except : pass
            col_value.append((name.value, value))
        values.append(col_value)
print values

판다를 사용함으로써 우리는 쉽게 읽을 수 있습니다.

import pandas as pd 
from pandas import ExcelWriter
from pandas import ExcelFile 

DataF=pd.read_excel("Test.xlsx",sheet_name='Sheet1')

print("Column headings:")
print(DataF.columns)

다음 사이트에서 테스트:https://repl.it 참조: https://pythonspot.com/read-excel-with-pandas/

다음은 Excel 파일을 읽고 1열에 있는 모든 셀을 인쇄하는 코드입니다(첫 번째 셀, 즉 헤더 제외).

import xlrd

file_location="C:\pythonprog\xxx.xlsv"
workbook=xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)
print(sheet.cell_value(0,0))

for row in range(1,sheet.nrows):
     print(sheet.cell_value(row,0))

제가 취한 접근 방식은 첫 번째 행에서 헤더 정보를 읽어 관심 열의 인덱스를 결정합니다.

질문에서 값도 문자열로 출력할 것이라고 언급했습니다.FORMAT 열 목록의 출력에 대한 형식 문자열을 동적으로 작성합니다.행은 새 행 문자로 구분된 값 문자열에 추가됩니다.

출력 열 순서는 FORMAT 목록의 열 이름 순서에 따라 결정됩니다.

아래의 코드에서는 FORMAT 목록에 있는 열 이름의 경우가 중요합니다.위 질문에서 FORMAT 목록에는 '핀코드'가 있고 엑셀에는 '핀코드'가 있습니다.아래에서는 작동하지 않습니다. 'PinCode'여야 합니다.

from xlrd import open_workbook
wb = open_workbook('sample.xls')

FORMAT = ['Arm_id', 'DSPName', 'PinCode']
values = ""

for s in wb.sheets():
    headerRow = s.row(0)
    columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == firstRow[x].value]
    formatString = ("%s,"*len(columnIndex))[0:-1] + "\n"

    for row in range(1,s.nrows):
        currentRow = s.row(row)
        currentRowValues = [currentRow[x].value for x in columnIndex]
        values += formatString % tuple(currentRowValues)

print values

위에 제공한 샘플 입력의 경우 이 코드 출력:

>>> 1.0,JaVAS,282001.0
2.0,JaVAS,282002.0
3.0,JaVAS,282003.0

저는 비단뱀 신보이기 때문에, 이 대답, 이 질문, 이 질문, 그리고 이 대답을 지지합니다.

는 openpyxl 라이브러리를 사용하여 읽었고,

import openpyxl
from pathlib import Path

xlsx_file = Path('C:\\Users\\Amit\\Desktop\\ReadExcel', 'ReadData.xlsx')
wb_obj = openpyxl.load_workbook(xlsx_file) 

# Read the active sheet:
sheet = wb_obj.active

for i in range(sheet.max_column):
    print(f'i = {i}')
    for row in sheet.iter_rows():
        print(row[i].value)

비록 저는 거의 항상 이것을 위해 판다를 사용하지만, 현재 제 작은 도구는 실행 파일로 포장되어 있고 판다를 포함하는 것은 과잉 살상입니다.그래서 저는 poida의 솔루션 버전을 만들어 명명된 튜플 목록을 만들었습니다.이 변경 사항이 있는 코드는 다음과 같습니다.

from xlrd import open_workbook
from collections import namedtuple
from pprint import pprint

wb = open_workbook('sample.xls')

FORMAT = ['Arm_id', 'DSPName', 'PinCode']
OneRow = namedtuple('OneRow', ' '.join(FORMAT))
all_rows = []

for s in wb.sheets():
    headerRow = s.row(0)
    columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == headerRow[x].value]

    for row in range(1,s.nrows):
        currentRow = s.row(row)
        currentRowValues = [currentRow[x].value for x in columnIndex]
        all_rows.append(OneRow(*currentRowValues))

pprint(all_rows)

언급URL : https://stackoverflow.com/questions/22169325/reading-excel-file-using-python-how-do-i-get-the-values-of-a-specific-column-wi

반응형