【问题标题】:Pandas read (Excel) cells, and return looked up valuesPandas 读取 (Excel) 单元格,并返回查找的值
【发布时间】:2019-08-09 09:23:11
【问题描述】:

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")

看起来不错。但我想学习 Pandas 的方法来做同样的事情。

除了下图,Pandas 的方式看起来如何?谢谢。

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

【问题讨论】:

  • 您还可以以文本形式(或重现数据框的代码)和字典发布原始数据吗?谢谢

标签: python pandas dataframe


【解决方案1】:

如果你有一个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(',')]))

【讨论】:

    【解决方案2】:

    有了给定的数据,我会先将map 字典添加到新列,然后将aggregate','.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
    

    【讨论】:

    • 感谢您的教导!希望您不介意我选择较早的答案,因为它对我来说更容易一些。 :)
    猜你喜欢
    • 2014-07-05
    • 1970-01-01
    • 2014-05-21
    • 2021-11-21
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多