簡體   English   中英

應用樣式器功能后如何刪除列? pandas.io.formats.style.Styler.hide_columns - 不工作

[英]How to delete column after applying styler function? pandas.io.formats.style.Styler.hide_columns - not work

應用樣式器后如何刪除列? 這是我的風格功能:

def highlight_late(x):
        c1 = 'background-color: red'
        #condition
        m = x['price_1'] < x['price_main_x']
        m2 = x['price_2'] < x['price_main_x']
        m3 = x['price_3'] < x['price_main_x']
        #empty DataFrame of styles
        df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    

    
#set column price_2 by condition
df1.loc[m, 'price_1'] = c1
df1.loc[m2, 'price_2'] = c1
df1.loc[m3, 'price_3'] = c1
df1.loc[m, 'url_x'] = c1
df1.loc[m2, 'url_y'] = c1
df1.loc[m3, 'url'] = c1

return df1

下面的方法返回我 TypeError: 'Styler' 對象不支持項目刪除

styles = myDF.style.apply(highlight_late, axis=None)
del styles['price_1']
del styles['price_2']
del styles['price_3']
styles.to_excel('test.xlsx')

我也嘗試:

mydf.style.hide_columns(['price_1', 'price_2', 'price_3']).to_excel('test.xlsx')

它不起作用,列不會隱藏。

即使來自https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.hide_columns.html 的這個簡單腳本也不起作用

df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "b", "c"])
df.style.hide_columns(["a", "b"])
df.to_excel('test2.xlsx')

嘗試hide_columns

styles = myDF.style.hide_columns(['price_1', 'price_2', 'price_3']).apply(highlight_late, axis=None)

或者刪除它們:

styles = myDF.style.hide_columns(['price_1', 'price_2', 'price_3'])
styles = styles.apply(highlight_late, axis=None)

您可以指定要寫入 Excel 的列。

cols = [col for col in styles.columns if col == condition]
df.to_excel('test2.xlsx', columns=cols)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM