【问题标题】:How to update excel column values based on dictionary in python如何根据python中的字典更新excel列值
【发布时间】:2021-05-08 13:48:20
【问题描述】:

我有一个 Excel 电子表格,如下所示:

费用.xlsx

|Amount|CategoryId|Date|
|:----|:------:|-----:|
| 123 | 1 | 2020-07-07|
| 321| 2 | 2020-07-07|

我有一本分类字典:

catDict = {1:'a', 2:'b'}

我将如何更改 excel 列“CategoryId”以匹配字典值:

Amount CategoryId Date
123 a 2020-07-07
321 b 2020-07-07

【问题讨论】:

    标签: python excel pandas


    【解决方案1】:

    使用 openpyxl,希望对您有所帮助!

    import openpyxl
    
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    dict = {1:'a', 2:'b'}
    
    sheet.cell(row=1, column=1, value='Amount')
    sheet.cell(row=1, column=2, value='CategoryId')
    sheet.cell(row=1, column=3, value='Date')
    row, column = 2,1
    for key, values in dict.items():
        sheet.cell(row=row, column=column, value=key)
        sheet.cell(row=row, column=column+1, value=values)
        sheet.cell(row=row, column=column+2, value='2020-07-07')
        row += 1
    file_name = 'sample.xlsx'
    workbook.save(filename=file_name)
    

    【讨论】:

      【解决方案2】:

      使用 openpyxl 您可以尝试以下操作:

      import openpyxl as opxl
      wb = opxl.load_workbook('expense.xlsx')
      ws = wb.active
      for i in range(1,ws.max_row+1):
          ws['B'+str(i)] = str(ws['B'+str(i)].value).replace('1','a').replace('2','b')
      wb.save('expense.xlsx')
      

      如果您有更多值要替换,那么我建议您也检查this 问题以改进这部分代码。

      旧答案: 你能用熊猫吗?如果是这样,您可以使用.replace()

      df = pd.read_csv('expense.xlsx') #Read excel
      catDict = {1:'a',2:'b'}
      
      df['CategoryId'] = df['CategoryId'].replace(catDict)
      #Alternatively one can use `.map()`
      
      df.to_excel('expense.xlsx') #Save back to excel
      

      【讨论】:

      猜你喜欢
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 2012-01-18
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      相关资源
      最近更新 更多