保存到excel熊猫时出现奇怪的问题

问题描述 投票:2回答:1

我在追求卓越时遇到了一些问题。我的数据框中有15列。我只希望将其中的7个写为excel,并在此过程中使用其他名称作为标题。

这是我的代码

cols = ['SN',  'Date_x','Material_x', 'Batch_x',  'Qty_x', 'Booked_x', 'State_x']
headers = ['SN', 'Date', 'Material', 'Batch',  'Qty', 'Booked', 'State']
df.style.apply(highlight_changes_ivt2, axis=None).to_excel(writer, columns =cols, header=headers, sheet_name="temp", index = False)

但是我有以下错误

  File "/home/week/anaconda3/envs/SC/lib/python3.7/site-packages/pandas/io/formats/style.py", line 235, in to_excel
engine=engine,
  File "/home/week/anaconda3/envs/SC/lib/python3.7/site-packages/pandas/io/formats/excel.py", line 735, in write
freeze_panes=freeze_panes,
  File "/home/week/anaconda3/envs/SC/lib/python3.7/site-packages/pandas/io/excel/_xlsxwriter.py", line 214, in write_cells
for cell in cells:
  File "/home/week/anaconda3/envs/SC/lib/python3.7/site-packages/pandas/io/formats/excel.py", line 684, in get_formatted_cells
for cell in itertools.chain(self._format_header(), self._format_body()):
 File "/home/week/anaconda3/envs/SC/lib/python3.7/site-packages/pandas/io/formats/excel.py", line 513, in _format_header_regular
f"Writing {len(self.columns)} cols but got {len(self.header)} "
ValueError: Writing 15 cols but got 7 aliases

我尝试进行调试..并设置pdb.set_trace()

df.style.apply(highlight_changes_ivt2, axis=None).to_excel(writer, columns =cols, header=headers, sheet_name="temp", index = False)
(Pdb) df.columns
      Index(['SN', 'Status_x', 'Material_x', 'Batch_x', 'Date_x', 'Quantity_x',
      'Booked_x', 'DiffQty_x', 'Status_y', 'Material_y', 'Batch_y',
      'Date_y', 'Quantity_y', 'Booked_y', 'DiffQty_y'],
      dtype='object')
(Pdb) 

尽管此代码在我的家用笔记本电脑上运行良好,但是只是想知道出什么问题了。区别仅在于此版本的python使用3.7版,而在家里使用3.8版

谢谢

excel pandas
1个回答
2
投票

通过示例让我在评论中阐述我的想法:

df = pd.DataFrame(np.arange(16).reshape(4,-1))

# this is the reference dataframe
np.random.seed(1)
ref_df = pd.DataFrame(np.random.randint(1,10,(4,4)))

# this is the function
def highlight(col, ref_df=None):
    return ['background-color: yellow' if c>r else '' 
                for c,r in zip(col, ref_df[col.name])]

# this works
df[[0,1,3]].style.apply(highlight, ref_df=ref_df).to_excel('style.xlsx', header=list('abc'))

输出:

image

© www.soinside.com 2019 - 2024. All rights reserved.