0

I'm trying to style a value and a value next to it in a pandas dataframe:

pandas_chart_sorted = pd.DataFrame({'Palabras': {0: 'papa', 1: 'pepe', 2: 'ja'}, 'Apariciones': {0: 2, 1: 2, 2: 1}})
    
    def filter_mark(val):
        if val in self.filters:
            color = 'red'
        else:
            color = 'black'
        return 'color: {}'.format(color)

    pandas_chart_sorted = pandas_chart_sorted.style.applymap(filter_mark)

    with pd.ExcelWriter(self.new_path) as writer:
        pandas_chart_sorted.to_excel(writer)

but I can't manage to style the value right next to it. So the output is this but it should look like this.

How can I do it?

pedro04
  • 1
  • 2
  • Is it possible to create a reproducible example? This prevents others to have to write code to reproduce the issue. For starters, for example you can include ths line of code: `pandas_chart_sorted = pd.DataFrame({'Palabras': {0: 'papa', 1: 'pepe', 2: 'ja'}, 'Apricinoes': {0: 2, 1: 2, 2: 1}})`but we need to be able to copy and paste your code and reproduce it. – David Erickson Sep 26 '20 at 03:34
  • Do you want to style the whole row or just the value next it in the dataframe? – Scott Boston Sep 26 '20 at 03:48
  • Just the value next to it, but I would very much like to learn how to do the whole row. – pedro04 Sep 26 '20 at 15:03
  • @pedro04 Added an update with both types of formatting. – Scott Boston Sep 27 '20 at 03:28
  • Thanks a lot. @DavidErickson, could you please reopen my post? I have already edited it like you suggested. – pedro04 Sep 27 '20 at 17:29

1 Answers1

1

Try this method:

df = pd.DataFrame(np.arange(25).reshape(5, -1))

def filter_mark(row):
    s = (row % 6 == 0) | (row.shift() % 6 == 0) 
    return [f'color: red' if i != False else '' for i in s]

def filter_row(row):
    return ['background: yellow'if (row % 10 == 0).any() else '' for _ in row]

df.style.apply(filter_mark, axis=1).apply(filter_row, axis=1)

Output:

enter image description here

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • Ok thank you! Could you explain a little bit what it's about? I'm kinda new to it. I understand that you check de condition s to give the style. But what does the condition s say? – pedro04 Sep 26 '20 at 15:00
  • Oh. The condition I am using here it to check to see if a number is divisible by 6, if so, then mark that value and the next value in that row by using `shift`. – Scott Boston Sep 26 '20 at 15:02