pandas 将数据从一个文件复制到模板文件,而不是复制到正确的列

m1m5dgzv  于 2023-11-15  发布在  其他
关注(0)|答案(1)|浏览(163)

我正在写一段代码,它从目录文件中选择数据,并将其复制到模板文件中,而不修改它。
目录文件中的一列(“产品类型”)决定了将数据复制到模板文件中的工作表。
模板文件列标题(我Map到匹配目录文件)在第三行。模板文件中的某些列在目录中没有列,因此这些列应该为空值
虽然Map名称是正确的,但数据没有复制到右列。

  1. import pandas as pd
  2. import openpyxl
  3. # Load the "catalogue" and "template" Excel files
  4. catalogue_file = r"catalogue.xlsx"
  5. catalogue_df = pd.read_excel(catalogue_file , sheet_name="Sheet_all")
  6. template_file = r'template.xlsx'
  7. template_workbook = openpyxl.load_workbook(template_file, data_only=True)
  8. # Create a mapping between column names in "catalogue" and "template"
  9. column_mapping = {
  10. 'PRODUCT ID': 'External ID',
  11. 'model': 'Model Number',
  12. 'Attribute1': 'Characteristic',
  13. 'Description': 'Model Name',
  14. 'PRODUCT TYPE': 'Product Type',
  15. }
  16. # Create a mapping between "PRODUCT TYPES" and sheet names in "template"
  17. type_to_sheet_mapping = {
  18. 'PRODUCT_TYPE_1': 'Template-type1',
  19. 'PRODUCT_TYPE_2': 'Template-type2',
  20. 'PRODUCT_TYPE_3': 'Template-type3',
  21. }
  22. for index, row in catalogue_df.iterrows():
  23. product_type = row['PRODUCT TYPE']
  24. data_to_copy = row.rename(column_mapping)
  25. # Check if the product type has a corresponding sheet name in the mapping
  26. if product_type in type_to_sheet_mapping:
  27. sheet_name = type_to_sheet_mapping[product_type]
  28. try:
  29. # Select the appropriate sheet in the "template" workbook
  30. template_sheet = template_workbook[sheet_name]
  31. # Find the last row and increment by 1
  32. last_row = template_sheet.max_row
  33. new_row = [last_row + 1] + data_to_copy.tolist()
  34. # Add the new data to the sheet
  35. template_sheet.append(new_row)
  36. except:
  37. print(f"{product_type} does not have a template sheet")
  38. template_workbook.save(r"updated_template.xlsx")

字符串

x8diyxa7

x8diyxa71#

我想你可以首先为模板文件中的所有列初始化一个new_row列表,然后遍历数据并将其复制到相应的列。

  1. # ...
  2. for index, row in catalogue_df.iterrows():
  3. product_type = row['PRODUCT TYPE']
  4. data_to_copy = row.rename(column_mapping)
  5. # Check if the product type has a corresponding sheet name in the mapping
  6. if product_type in type_to_sheet_mapping:
  7. sheet_name = type_to_sheet_mapping[product_type]
  8. try:
  9. # Select the appropriate sheet in the "template" workbook
  10. template_sheet = template_workbook[sheet_name]
  11. # Find the last row and increment by 1
  12. last_row = template_sheet.max_row
  13. new_row = [None] * (len(column_mapping) + 1) # Initialize with None for all columns
  14. for col_name, value in data_to_copy.items():
  15. if col_name in column_mapping:
  16. col_index = list(column_mapping.values()).index(column_mapping[col_name])
  17. new_row[col_index + 1] = value
  18. # Add the new data to the sheet
  19. template_sheet.append(new_row)
  20. except:
  21. print(f"{product_type} does not have a template sheet")
  22. # ...

字符串

展开查看全部

相关问题