I can highlight a column using the syntax
import pandas as pd
df = pd.DataFrame([[1,0],[0,1]])
df.style.apply(lambda x: ['background: lightblue' if x.name == 0 else '' for i in x])
Similarly I can highlight a row by passing axis=1
:
df.style.apply(lambda x: ['background: lightgreen' if x.name == 0 else '' for i in x],
axis=1)
However I can't work out how to do both at once; the problem is that when I use applymap
, I only get the values, not the names of the series that they come from.
You can highlight a row in Pandas dataframe using Dataframe.style property as shown in the below example: Here, apply () calls lambda function highlight for every row of the dataset. If the row index is 3 or 6, then the row is highlighted. Further Reading…
Here, apply () calls lambda function highlight for every row of the dataset. If the row index is 3 or 6, then the row is highlighted. Further Reading… Table Visualization ¶ This section demonstrates visualization of tabular data using the Styler class. For information on visualization with charting please see Chart Visualization .
In the post, we'll use the following DataFrame, which consists of several rows and columns: The first way to compare the two columns of a DataFrame is by chaining: We need to enter the column names. After the execution the differences between the two columns will be highlighted in yellow:
Using pandas only (no multiprocessing tools, no map-reduce tools), the max rows you can load in pandas is dependent on your machine’s available RAM. Simply, your machine will continue to load the data until it exceeds its capacity to store the object in working memory until either your machine (or the process) crashes.
How about doing something like this? Enumerate the column and check the index while building up the style list:
df.style.apply(lambda x: ['background: lightblue' if x.name == 0 or i == 0 else ''
for i,_ in x.iteritems()])
Or if you have color preference:
df.style.apply(lambda x: [('background: lightblue' if x.name == 0
else ('background: lightgreen' if i == 0 else ''))
for i,_ in x.iteritems()])
You can also chain your styles:
import pandas as pd
df = pd.DataFrame([[1,0],[0,1]])
df.style\
.apply(lambda x: ['background: lightblue' if x.name == 0 else '' for i in x])\
.apply(lambda x: ['background: lightgreen' if x.name == 0 else '' for i in x], axis=1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With