【问题标题】:Pandas Dataframe Styles are not working with Jupyter NotebookPandas 数据框样式不适用于 Jupyter Notebook
【发布时间】:2020-05-21 15:11:01
【问题描述】:

我有一个数据框,它是使用我从 excel 文件中读取的列表和其他数据框构建的。 我想要做的是,我只需要将背景颜色应用到数据框的第一行,然后将其导出到 Excel 中。 下面的代码按预期正确地完成了工作。(数据有问题)

问题是我应用于数据框的样式未反映在 Excel 工作表中。我正在使用 Jupyter 笔记本。 请提出一种在 excel 中获取样式的方法。

import pandas as pd

sheet1 = r'D:\dinesh\input.xlsx'
sheet2 = "D:\dinesh\lookup.xlsx"
sheet3 = "D:\dinesh\Output.xlsx"
sheetname = 'Dashboard Índice (INPUT)'

print('Started extracting the Crime Type!')
df1 = pd.read_excel(sheet1,sheet_name = 'Dashboard Índice (INPUT)',skiprows=10, usecols = 'B,C,D,F,H,J,L,N,P', encoding = 'unicode_escape')

crime_type = list(df1.iloc[:0])[3:]
print(f'crime_types : {crime_type}')
df1  = (df1.drop(columns=crime_type,axis=1))
cols = list(df1.iloc[0])

print(f'Columns : {cols}')
df1.columns = cols
df1  = (df1[1:]).dropna()

final_data = []
for index, row in df1.iterrows():   
    sheetname   = (f'{row[cols[1]]:0>2d}. {row[cols[0]]}')    
    cnty_cd     = [row[cols[0]], row[cols[1]], row[cols[2]]]
    wb = pd.ExcelFile(sheet2)

    workbook = ''.join([workbook for workbook in wb.sheet_names if workbook.upper() == sheetname])         
    if workbook:
        df2 = pd.read_excel(sheet2, sheet_name = workbook, skiprows=7, usecols ='C,D,H:T', encoding = 'unicode_escape')

        df2_cols = list(df2.columns)  
        final_cols = cols + df2_cols
        df2 = df2.iloc[2:]        
        df2 = df2.dropna(subset=[df2_cols[1]])

        for index2, row2 in df2.iterrows():             
            if row2[df2_cols[1]].upper() in crime_type:
                s1       = pd.Series(cnty_cd)                
                df_rows  = (pd.concat([s1, row2], axis=0)).to_frame().transpose()             
                final_data.append(df_rows)
                break                                                                                 
    else:
        print(f'{sheetname} does not exists!')

df3 = pd.concat(final_data)
df3.columns = final_cols
df_cols     = (pd.Series(final_cols, index=final_cols)).to_frame().transpose()
df_final    = (pd.concat([df_cols,df3], axis=0, ignore_index=True, sort=False))
df_final.style.apply(lambda x: ['background: blue' if x.name==0 else '' for i in x], axis=1)
df_final.to_excel(sheet3, sheet_name='Crime Details',index=False,header = None)

print(f'Sucessfully created the Output file to {sheet3}!')     

【问题讨论】:

  • 和你的问题没有直接关系,但你为什么用.iterrows()?这是单调的,而且非常缓慢。您能解释一下您正在执行的操作吗?

标签: python r excel pandas dataframe


【解决方案1】:

您需要导出到 excel 样式数据框而不是无样式数据框,因此您需要将样式链接在一起并发送到 Excel,类似于文档here 中所示,或者分配样式数据框并使用它发送到 Excel。
根据您的代码,后者可能看起来像这样:

df_styled = df_final.style.apply(lambda x: ['background: blue' if x.name==0 else '' for i in x], axis=1)
df_styled.to_excel(sheet3,, sheet_name='Crime Details',index=False, header = None, engine='openpyxl')

here 所述,您需要使用 OpenPyXL 或 XlsxWriter 引擎进行导出。

【讨论】:

  • 我也试过你上面的代码。但没有运气。样式仍然没有应用到工作表中。
  • 并非所有样式都能够传递给 Excel。但这个应该是,我想。无法访问您的东西我没有测试所有内容。您的原始代码根本无法工作。我很容易挖出的example 没有转到 Excel 部分,所以我需要更多地挖掘我实际将格式传递给 Excel 的地方,并提出一个更好的测试来将你的代码合并到或比较去我的。
猜你喜欢
  • 2019-02-05
  • 2019-12-22
  • 2018-02-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 2018-08-25
  • 2016-09-03
相关资源
最近更新 更多