读取(Excel)单元格,并返回查找到的值

2024-05-21 11:35:09 发布

您现在位置:Python中文网/ 问答频道 /正文

Excel文件中的一列显示了某些描述的简短形式。它们在字典里是一对一的关系

我想逐个查找它们,并将查找到的值与简短的表单并排写入一个新文件

Xlrd和xlwt是基本的,所以我使用它们:

product_dict = {
"082" : "Specified brand(s)",
"035" : "Well known brand",
"069" : "Brandless ",
"054" : "Good middle class restaurant",
"062" : "Modest class restaurant"}

import xlwt, xlrd

workbook = xlrd.open_workbook("C:\\file.xlsx")
old_sheet = workbook.sheet_by_index(0)

book = xlwt.Workbook(encoding='cp1252', style_compression = 0)
sheet = book.add_sheet('Sheet1', cell_overwrite_ok = True)

for row_index in range(1, old_sheet.nrows):
    new_list = []   
    Cell_a = str(old_sheet.cell(row_index, 0).value)

    for each in Cell_a.split(", "):

        new_list.append(product_dict[each])

    sheet.write(row_index, 0, Cell_a)
    sheet.write(row_index, 1, "; ".join(new_list))

book.save("C:\\files-1.xls")

看起来不错。但我想学熊猫也一样

熊猫的样子怎么样,除了下面?谢谢你

data = {'Code': ["082","069","054"]}
df = pd.DataFrame(data)

enter image description here


Tags: 文件newindexcellproductolddictlist
2条回答

如果有python字典形式的查找字典,可以执行以下操作:

import pandas as pd

lookup_dict = {'1': 'item_1', '2':'item_2'}

# Create example dataframe
df_to_process = pd.DataFrame()
df_to_process['code'] = ['1, 2', '1', '2']

# Use .apply and lambda function to split 'code' and then do a lookup on each item
df_to_process['code_items'] = df_to_process['code'].apply(lambda x: '; '.join([lookup_dict[code] for code in x.replace(' ','').split(',')]))

举你的例子:

import pandas as pd

product_dict = {
"082" : "Specified brand(s)",
"035" : "Well known brand",
"069" : "Brandless ",
"054" : "Good middle class restaurant",
"062" : "Modest class restaurant"}

data = {'Code': ["082","069","054"]}
df = pd.DataFrame(data)

df['code_items'] = df['Code'].apply(lambda x: '; '.join([product_dict[code] for code in x.replace(' ','').split(',')]))

有了给定的数据,我将首先^{}将字典添加到一个新列,然后^{}使用','.join

final=df.assign(New=df.Code.map(product_dict)).agg(','.join).to_frame().T

          Code                                                New
0  082,069,054  Specified brand(s),Brandless ,Good middle clas...

其中:

print(df.assign(New=df.Code.map(product_dict)))

是:

  Code                           New
0  082            Specified brand(s)
1  069                    Brandless 
2  054  Good middle class restaurant

相关问题 更多 >