본문 바로가기

개발하자

Excel 데이터에서 Python 사전 만들기

반응형

Excel 데이터에서 Python 사전 만들기

나는 값들로 사전을 만들고 싶다, 나는 엑셀 셀들로부터 얻는다, 나의 코드는 아래와 같다,

wb = xlrd.open_workbook('foo.xls')
sh = wb.sheet_by_index(2)   
for i in range(138):
    cell_value_class = sh.cell(i,2).value
    cell_value_id = sh.cell(i,0).value

그리고 나는 아래와 같이 엑셀 셀에서 나오는 값들로 구성된 사전을 만들고 싶다.

{'class1': 1, 'class2': 3, 'class3': 4, 'classN':N}

제가 이 사전을 어떻게 만들 수 있는지 아세요?




d = {}
wb = xlrd.open_workbook('foo.xls')
sh = wb.sheet_by_index(2)   
for i in range(138):
    cell_value_class = sh.cell(i,2).value
    cell_value_id = sh.cell(i,0).value
    d[cell_value_class] = cell_value_id



아니면 시도해 볼 수도 있다.

from pandas import *
xls = ExcelFile('path_to_file.xls')
df = xls.parse(xls.sheet_names[0])
print df.to_dict()



나는 찬성한다:

wb = xlrd.open_workbook('foo.xls')
sh = wb.sheet_by_index(2)   
lookup = dict(zip(sh.col_values(2, 0, 138), sh.col_values(0, 0, 138)))



만약 당신이 그것을 csv로 변환할 수 있다면 이것은 매우 적합하다.

import dataconverters.commas as commas
filename = 'test.csv'
with open(filename) as f:
      records, metadata = commas.parse(f)
      for row in records:
            print 'this is row in dictionary:'+row



이 스크립트를 사용하여 Excel 데이터 테이블을 사전 목록으로 변환할 수 있습니다.

import xlrd

workbook = xlrd.open_workbook('foo.xls')
workbook = xlrd.open_workbook('foo.xls', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # The row where we stock the name of the column
for col in range(worksheet.ncols):
    first_row.append( worksheet.cell_value(0,col) )
# transform the workbook to a list of dictionaries
data =[]
for row in range(1, worksheet.nrows):
    elm = {}
    for col in range(worksheet.ncols):
        elm[first_row[col]]=worksheet.cell_value(row,col)
    data.append(elm)
print data



판다를 이용해서 이렇게 할 수 있습니다. 팬더 가져오기 및 Excel을 팬더 데이터 프레임으로 읽습니다.

import pandas as pd
file_path = 'path_for_your_input_excel_sheet'
df = pd.read_excel(file_path, encoding='utf-16')

를 사용하여 팬더 데이터 프레임을 사전으로 변환할 수 있습니다.

df.to_dict()

이것은 당신이 읽은 엑셀 시트의 사전을 제공할 것이다.

일반적인 예:

df = pd.DataFrame({'col1': [1, 2],'col2': [0.5, 0.75]},index=['a', 'b'])

>>> df

col1 col2 a 1 0.50 b 2 0.75

>>> df.to_dict()

{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}




다음을 위한 PyPI 패키지도 있습니다. 그것은 엑셀과 csv 파일을 분석하고 사전 배열로 반환하는 것이다. 각 행은 배열에서 사전으로 표시됩니다.

다음과 같이:

Python 3.9.0 (default, Dec  6 2020, 18:02:34)
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

# Import the library
>>> from sheet2dict import Worksheet

# Create an object
>>> ws = Worksheet()

# return converted rows as dictionaries in the array 
>>> ws.xlsx_to_dict(path='Book1.xlsx')
[
    {'#': '1', 'question': 'Notifications Enabled', 'answer': 'True'}, 
    {'#': '2', 'question': 'Updated', 'answer': 'False'}
]



팬더를 사용하여 Excel 데이터를 파이썬 사전 목록으로 변환하려면 다음을 수행하는 가장 좋은 방법을 사용하십시오.

excel_file_path = 'Path to your Excel file'
excel_records = pd.read_excel(excel_file_path)
excel_records_df = excel_records.loc[:, ~excel_records.columns.str.contains('^Unnamed')]
records_list_of_dict=excel_records_df.to_dict(orient='record')
Print(records_list_of_dict)



를 사용하는 경우 코드 아래의 pyxl을 열면 다음과 같은 도움이 될 수 있습니다.

import openpyxl
workbook = openpyxl.load_workbook("ExcelDemo.xlsx")
sheet = workbook.active
first_row = [] # The row where we stock the name of the column
for col in range(1, sheet.max_column+1):
    first_row.append(sheet.cell(row=1, column=col).value)
data =[]
for row in range(2, sheet.max_row+1):
    elm = {}
    for col in range(1, sheet.max_column+1):
        elm[first_row[col-1]]=sheet.cell(row=row,column=col).value
    data.append(elm)
print (data)

크레딧:




나는 많은 방법을 시도했지만 이것이 내가 찾은 가장 효과적인 방법이다:

import pyexcel as p

def read_records():
    records = p.get_records(file_name="File")
    products = [row for row in records]
    return products

반응형