【问题标题】:How to return a specific cell that have color style and font style for iloc[1,1] only?如何仅返回具有 iloc[1,1] 的颜色样式和字体样式的特定单元格?
【发布时间】:2017-09-24 17:22:27
【问题描述】:

我有一个数据框,下面是我的颜色代码:

   def color (val):
    if final.iloc[1,1]<final.iloc[1,0]:
        return "background-color: green"
    else:
        return "background-color: red"

我希望只返回 final.iloc[1,1] 以具有绿色背景,如果应用上述代码,我的整个数据框已经变为绿色。

我也希望final.iloc[1,1] 能够更改字体样式,有人可以分享我的想法吗?

【问题讨论】:

  • 这可能会有所帮助....stackoverflow.com/q/38511373/6524169
  • 不能,我已经尝试过了,但就我而言,我只需要一个单元格而不是整个数据框
  • 我已经更新了我的帖子。

标签: python pandas dataframe


【解决方案1】:

你可以使用:

import pandas as pd
import numpy as np

np.random.seed(100)
df =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
print (df)

def highlight_col(x):
    #copy df to new - original data are not changed
    df = x.copy()
    #set default values to all values
    df.loc[:,:] = 'background-color: ""'
    #set by condition
    if x.iloc[1,1]<x.iloc[1,0]:
        df.iloc[1,1] = 'background-color: red'
    else:
        df.iloc[1,1] = 'background-color: green'
    return df    

df.style.apply(highlight_col, axis=None)

【讨论】:

  • 还是不行,我得到这个错误 'NoneType' object has no attribute 'style'
  • 您可以尝试编辑的答案。以前的解决方案是错误的。
  • 我尝试应用此df.iloc[1,1] = 'background-color: red' 也无法显示此错误 'unorderable types: str()
  • 红色使用np.random.seed(170)
  • 是的,我尝试了,但是得到了这个错误**'NoneType' object has no attribute 'iloc'**
【解决方案2】:
import pandas as pd
import numpy as np

ex1 = pd.DataFrame([
        [1, 2, 3],
        [2, 1, 4],
        [5, 3, 1]
    ], list('ABC'), list('XYZ'))

ex2 = pd.DataFrame([
        [1, 2, 3],
        [1, 9, 4],
        [5, 3, 1]
    ], list('ABC'), list('XYZ'))

def hl(x):
    r = 'background-color: red'
    g = 'background-color: green'
    c = g if x.iloc[1, 1] < x.iloc[1, 0] else r
    y = pd.DataFrame('', index=x.index, columns=x.columns)
    y.iloc[1, 1] = c
    return y

ex1.style.apply(hl, axis=None)

ex2.style.apply(hl, axis=None)

【讨论】:

  • 谢谢@piRSquared
猜你喜欢
  • 2020-03-25
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
  • 2011-09-11
相关资源
最近更新 更多