簡體   English   中英

熊貓風格背景漸變未顯示在 jupyter 筆記本中

[英]Pandas style background gradient not showing in jupyter notebook

我正在嘗試打印帶有背景漸變的 Pandas 數據框以提高可讀性。 我試圖將我在文檔中找到的內容應用於一個簡單的用例,但我無法讓 jupyter notebook 實際打印帶有顏色的表格 - 我一直在獲取純數據框。 小例子:

import seaborn as sns
import pandas as pd


cm = sns.light_palette('green', as_cmap=True)
df_res = pd.DataFrame(index =['foo','bar'],columns = ['Value 1','Value 2','Value 3'])
df_res.loc['foo'] = [-.5*100, .3,.2]
df_res.loc['bar'] = [.3*100, .6,.9]
df_res.style.background_gradient(cmap=cm)

只是打印

這個簡單的數據框 .

我嘗試了不同的印刷技術,即

pretty = df_res.style.background_gradient(cmap=cm)
display(pretty)

或者

print(pretty)

或不同的顏色圖

df_res.style.background_gradient(cmap='viridis')

但它們都不起作用。 我也嘗試過樣式器是否有效,但至少 applymap 函數可以完成它應該做的事情:

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color
df_res.style.applymap(color_negative_red)

哪個打印

所以不確定為什么 background_gradient 似乎沒有任何效果。

編輯:剛剛找到原因。 這是一個簡單的修復,但如果其他人遇到同樣的問題,我會保持這個狀態。 顯然,pandas 用元素作為對象而不是浮點數來初始化數據幀。 如此簡單的將初始化更改為

df_res = pd.DataFrame(index =['foo','bar'],columns = ['Value 1','Value 2','Value 3']).astype('float')

解決了這個問題。

您的數據框的 dtypes 是“對象”而不是數字。

首先,將數據框中的 dtype 更改為數字。

df_res.apply(pd.to_numeric).style.background_gradient(cmap=cm)

輸出: 在此處輸入圖片說明


注意數據類型:

import seaborn as sns
import pandas as pd


cm = sns.light_palette('green', as_cmap=True)
df_res = pd.DataFrame(index =['foo','bar'],columns = ['Value 1','Value 2','Value 3'])
df_res.loc['foo'] = [-.5*100, .3,.2]
df_res.loc['bar'] = [.3*100, .6,.9]
df_res.info()

輸出:

<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, foo to bar
Data columns (total 3 columns):
Value 1    2 non-null object
Value 2    2 non-null object
Value 3    2 non-null object
dtypes: object(3)
memory usage: 144.0+ bytes

暫無
暫無

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

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