0

I am trying to count the number of words in each row on a column using

df['new_column'] = df.column1.apply(lambda x: len(str(x).split(' ')))

This is creating a new column in my df with the number of words from column'column1'. I want to color the cells from 'column1' which, have less than 5 words. Is there a way I can do this with python applicable to all rows in the column 'column1'?

column 1
Camiseta Tecnica hombre barata
deportivas calcetin hombres running
Camiseta Tecnica mejores deportivas running Camiseta

Thanks a lot

Ema
  • 21
  • 2
  • Does this answer your question? [Pandas style function to highlight specific columns](https://stackoverflow.com/questions/41654949/pandas-style-function-to-highlight-specific-columns) – Salma Elshahawy Sep 15 '20 at 11:59

1 Answers1

0

You could use the pandas Styler doing the transformation within the color change function.

# color change func
def change_colour(x):
    return ['background-color: green' if len(x[0].split()) < 5 else '']

# pass in the series as a df using to_frame()
df['column1'].to_frame().style.apply(change_colour, axis=1)

Try this to export to excel:

df['column1'].to_frame().style.apply(change_colour,axis=1).
to_excel('test.xlsx', engine='openpyxl')

https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html

GhandiFloss
  • 392
  • 1
  • 6
  • It returns two errors: TypeError: '<' not supported between instances of 'str' and 'int' and AttributeError: 'Series' object has no attribute 'style' I have tried before with .style and got the same error – Ema Sep 15 '20 at 10:45
  • can you post your df please? – GhandiFloss Sep 15 '20 at 10:48
  • I have updated in the description, it is just a column with many rows (I just passed 3 of them), on each row I have several words to count and highlight cells where less than 5 words are found – Ema Sep 15 '20 at 11:22
  • Hi, thanks a lot but still not working, I believe there's something wrong when printing to excel, like the code looks fine, also from the example provided above by Salma, the code has nothing wrong just that the color is not printed in excel, there's something Im missing here I guess – Ema Sep 15 '20 at 12:40
  • I didn't know you wanted to export to excel. I have tested the edit above and it now works – GhandiFloss Sep 15 '20 at 13:12