【问题标题】:Python Pandas StylePython Pandas 风格
【发布时间】:2018-05-02 18:54:33
【问题描述】:

我正在尝试更改 Pandas 中 df3 中 df1 中字符串的字体颜色。我的数据集是:

df1 = [ "i like to shop at store a." , "he likes to shop at the store b.", "she is happy to shop at store c.", 'we want to shop at the store d.']
df2 = [ "store a", "store b", "store c", 'store d' ]
df3 = [ "like to", "likes to shop", "at store" ]

myDataSet = list(zip(df1,df2))
df = pd.DataFrame(data = myDataSet, columns=['df1', 'df2'])

要更改 df1 中字符串的颜色,我使用了以下内容,但出现了无效的语法错误。请帮忙。

def color_negative_red(df1):
    x for x in df3 if x in df["df1"]
    return 'color: %s' % color
s = df.style.applymap(color_negative_red)
s

【问题讨论】:

    标签: python pandas pandas-styles


    【解决方案1】:

    使用字边界检查带有contains 的子字符串并返回DataFrame of styles:

    def color_substrings(x):
        c1 = 'background-color: red'
        c2 = '' 
        pat = '|'.join([r'\b{}\b'.format(x) for x in df3])
        mask = df["df1"].str.contains(pat)
        df1 =  pd.DataFrame(c2, index=df.index, columns=df.columns)
        #modify values of df1 column by boolean mask
        df1.loc[mask, 'df1'] = c1
        return df1
    
    df.style.apply(color_substrings, axis=None)
    

    注意 - 如果只想选择子字符串,目前还不支持。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 2016-04-15
      • 2011-05-08
      • 2011-07-18
      • 2011-07-22
      • 2010-10-03
      相关资源
      最近更新 更多