【发布时间】: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)
【问题讨论】:
-
您还可以以文本形式(或重现数据框的代码)和字典发布原始数据吗?谢谢