30288

Coloring Single Column of Pandas Dataframe.to_html()

Question:

Before this is marked as duplicate, I have tried the code from the following topics and none has worked for me thus far:

[<a href="https://stackoverflow.com/questions/44388149/colouring-one-column-of-pandas-dataframe" rel="nofollow">Colouring one column of pandas dataframe</a> ]

[<a href="https://stackoverflow.com/questions/43839112/format-the-color-of-a-cell-in-a-panda-dataframe-according-to-multiple-conditions" rel="nofollow">Format the color of a cell in a panda dataframe according to multiple conditions</a> ]

[<a href="https://stackoverflow.com/questions/42408246/how-to-color-selected-columns-in-python-dataframe" rel="nofollow">how to color selected columns in python dataframe?</a> ]

I have code that produces three pandas dataframe that looks like this:

RowName Orders Market StartTime StopTime Status good A 9 gold 10:00:00 10:09:45 . . . bad B 60 silver 07:54:43 08:02:12 RowName Orders Market StartTime StopTime Status good E 19 plat. 10:00:00 10:09:45 . . bad F 54 mercury 07:54:43 08:02:12 RowName Orders Market StartTime StopTime Status great D 3 alum. 10:00:00 10:09:45 . . ok C 70 bronze 07:54:43 08:02:12

where the Status column is set as the index of each frame

<strong>For each frame</strong>, I want to highlight the StartTime column with the value #D42A2A (aka red) regardless of what value is in a given cell.

How can this be done?

MOST RECENT FAILED ATTEMPTS:

<ol><li>

def column_style(col): if col.Name == 'StartTime': return pd.Series('bgcolor: #d42a2a', col.index)

</li> <li>

def col_color(data): color = 'red' if data != '' else 'black' return 'color: %s' %color frame.style.applymap(col_color, subset=['StartTime'])

</li> </ol>

but this also fails.

NOTE:

<ol><li>

I am using VI within a linux shell

</li> <li>

The entire script is being called by IE (internet explorer) so the output of the script is html

</li> <li>

I am using BS (beautifulsoup) to scrape data from a few sites and the aggregating the results onto one page {*after scraping the initial website and creating the required website (call it Page1), I tried to scrape Page1 in the same script and add in the html lines via the .attrs method, but this "fails", i.e. the webserver times out during the run}

</li> </ol>

Answer1:

Let's try this:

import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1) df.iloc[0, 2] = np.nan def highlight_column(s, col): return ['background-color: #d42a2a' if s.name == col else '' for v in s.index] df.style.apply(highlight_column, col = 'B')

Output:

<a href="https://i.stack.imgur.com/ZtZ4J.jpg" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/ZtZ4J.jpg" data-original="https://i.stack.imgur.com/ZtZ4J.jpg" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

Answer2:

If anyone is using BeautifulSoup to parse a website and then using pandas to create a DataFrame that you may want to add styles to, you can do something like:

(before using this you have already; imported beautifulsoup, scraped your site and created your dataframe)

variable_name = beautifulsoup(dataframe_name.to_html())

list = []

`for table in variable_name.findAll('table'):` `for tbody in variable_name.findAll('table'):` `for td in variable_name.findAll('tbody'):` `list.append(td)`

list[td_index]['attribute_name'] = 'attribute_value'

This will add your all your table data to a list and you can select any element from that list and add/update a tag attribute

(if more efficient way please comment to help improve)

Recommend

  • How can I have kendo NumericTextBox keep focus during highlighting in a kendo window?
  • Programmatically selecting hyperlinkbuttons
  • Label transition issue
  • Using Shiny actionButton() function in onRender() function of htmlWidgets
  • Select / Focus cell using SlickGrid
  • Image swiping and changing with buttons as well
  • How to use optional attributes in web service update messages (DTOs)?
  • How to set crop box in jquery cropper
  • carouFredSel add class to active slide
  • How to highlight a particular row in a page of a DevExpress MVC GridView?
  • TTK progress bar blocked when sending email
  • Can I make Visual Studio's code completion window more like Eclipse (Java)?
  • Knockout - How to bind outer container css from set of checkboxes?
  • How do I wrap a span around a section of text in javascript?
  • ContextCompat.getcolor() going to null object reference
  • How to realize with WinForms in C# something like an image with map areas in a homepage (at hooverin
  • How to read the param value from the object tag using javascript
  • Compare a column between 2 csv files and write differences using Python
  • Android Ripple: How do other apps make their ripple so transparent without affecting the original co
  • href inside href [duplicate]
  • Formatting a text in a table cell with PHPWord e.g. bold, font, size e.t.c
  • How to filter on year and quarter in pandas
  • Convert two columns Pandas data frame to dictionary of list with first column as keys
  • Color time-series based on column values in pandas
  • Google Maps api v3 get start and end coordinates of a street
  • C# List of Panels
  • Image map in Flex
  • R convert summary result (statistics with all dataframe columns) into dataframe
  • gspread or such: help me get cell coordinates (not value)
  • How to Cache Real-time Data?
  • Error when parsing timestamp with pandas read_csv
  • Insert into database using onclick function
  • How to add date and time under each post in guestbook in google app engine
  • JSON with duplicate key names losing information when parsed
  • align graphs with different xlab
  • Return words with double consecutive letters
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?