Pandas apply().to_excel() 得到 DataFrame 不可调用

Pandas apply().to_excel() got DataFrame is not callable

    empty_stock_list = [
    {
      'row_index': <num>,
      'column_index': <num>
    },
    ...
    ]

    with pd.ExcelWriter(OUTPUT_FILE, engine='xlsxwriter') as writer:
        df = pd.concat([header_row, data_price], ignore_index=False, sort=False).reset_index(drop=True)
        
        df_color = df.copy()
        df_color.iloc[:,:] = 'font-color: black'
        for empty_stock in empty_stock_list:
            df_color.iloc[empty_stock['row_index'], empty_stock['column_index']] = 'font-color: #FF0000'

        df.style.apply(df_color, axis=None).\
            to_excel(writer, sheet_name=sheet_name, index=False, header=None)

我上面有这段代码,但总是得到这个错误:TypeError: 'DataFrame' object is not callable。基本上我想要做的是在库存为空时将单元格颜色变为红色(基于数据 row_indexcolumn_index)。

试图按照文档进行操作,但我似乎无法做到这一点。

以下是追溯错误信息:

Traceback (most recent call last):
  File "main.py", line 129, in <module>
    df.style.apply(df_color, axis=None).\
  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/style.py", line 229, in to_excel
    formatter.write(
  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/excel.py", line 734, in write
    writer.write_cells(
  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/excel/_xlsxwriter.py", line 212, in write_cells
    for cell in cells:
  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/excel.py", line 688, in get_formatted_cells
    for cell in itertools.chain(self._format_header(), self._format_body()):
  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/excel.py", line 590, in _format_regular_rows
    for cell in self._generate_body(coloffset):
  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/excel.py", line 674, in _generate_body
    styles = self.styler._compute().ctx
  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/style.py", line 625, in _compute
    r = func(self)(*args, **kwargs)
  File "/home/michaelharley/.local/lib/python3.8/site-packages/pandas/io/formats/style.py", line 642, in _apply
    result = func(data, **kwargs)
TypeError: 'DataFrame' object is not callable

我正在使用这些依赖项:

我认为您需要创建函数并传递给 Styler.apply 并将 font-color 更改为 color:

def func(df):

    df_color = pd.DataFrame('color: black', index=df.index, columns=df.columns)
    
    for empty_stock in empty_stock_list:
        i = empty_stock['row_index']
        j = empty_stock['column_index']
        df_color.iloc[i,j] = 'color: #FF0000'
    return df_color


with pd.ExcelWriter(OUTPUT_FILE, engine='xlsxwriter') as writer:
    df = pd.concat([header_row, data_price], 
                    ignore_index=False, 
                    sort=False).reset_index(drop=True)
        
    (df.style.apply(func, axis=None)
       .to_excel(writer, sheet_name=sheet_name, index=False, header=None))