yoshiserry
yoshiserry

Reputation: 21345

Color data items in a pandas dataframe based on value

I have a dataframe with some data (names, amount_x, amount_y and "diff" column which subtracts amount X and Y.

I would like to color the cells, where "diff" is a positive number (and make them green) and where it is negative, make it red)?

Is this possible?

Upvotes: 6

Views: 12692

Answers (2)

Pramit
Pramit

Reputation: 1411

Have not tried the styling in pandas but, one could give python wrapper for ggplot(https://github.com/yhat/ggpy) a try,

# One might get some dependency errors in-regards to pandas-timeseries 
# module and statsmodels
# if that happens try, pip install --upgrade statsmodels 

sudo pip install ggplot
# Assuming one has a dataframe then,
from ggplot import *
# internally, it will figure out the unique values for VariableC and 
# define a color change automatically
ggplot(aes(x='variableA', y='variableB', color='VariableC'), 
        data=data_df) + geom_point()

Hopefully, that was helpful ...

Upvotes: 1

Simon
Simon

Reputation: 173

Starting from Pandas version 0.17.1

You can use style.applymap with this kind of line

df.style.applymap(color, subset=['diff'])

More infos and example here : https://pandas.pydata.org/pandas-docs/stable/style.html

Upvotes: 5

Related Questions