Python Conditionally Add Class to td Tags in HTML Table

2024/10/13 9:19:26

I have some data in the form of a csv file that I'm reading into Python and converting to an HTML table using Pandas.

Heres some example data:

name  threshold  col1 col2 col3
A     10         12   9    13
B     15         18   17   23
C     20         19   22   25

And some code:

import pandas as pd
df = pd.read_csv("data.csv")
table = df.to_html(index=False)

This creates the following HTML:

<table border="1" class="dataframe"><thead><tr style="text-align: right;"><th>name</th><th>threshold</th><th>col1</th><th>col2</th><th>col3</th></tr></thead><tbody><tr><td>A</td><td>10</td><td>12</td><td>9</td><td>13</td></tr><tr><td>B</td><td>15</td><td>18</td><td>17</td><td>23</td></tr><tr><td>C</td><td>20</td><td>19</td><td>22</td><td>25</td></tr></tbody>
</table>

No I want to conditionally add a class to each cell in the html table if its value is less than a certain threshold. The threshold is different for each row in the table.

So given the example data above, I want to add a class, class="custom" to cell col2 with name A and to cell col1 with name C. In CSS, I will then fill the cell color as red if it has the "custom" class.

The result would be something like:

<table border="1" class="dataframe"><thead><tr style="text-align: right;"><th>name</th><th>threshold</th><th>col1</th><th>col2</th><th>col3</th></tr></thead><tbody><tr><td>A</td><td>10</td><td>12</td><td class="custom">9</td><td>13</td></tr><tr><td>B</td><td>15</td><td>18</td><td>17</td><td>23</td></tr><tr><td>C</td><td>20</td><td class="custom">19</td><td>22</td><td>25</td></tr></tbody>
</table>

How can this be achieved using Beautiful Soup?

Answer

Using BeautifulSoup you can add a class to the tags attrs as you would set a key/value in a dictionary:

soup = BeautifulSoup(html,"html.parser")for row in soup.select("tbody tr"):tds = row.find_all("td")     if int(tds[3].text) < int(tds[1].text):tds[3]["class"] = "custom"if int(tds[2].text) < int(tds[1].text):tds[2]["class"] = "custom"

Which using your input html would give you:

<html><body><table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>name</th>
<th>threshold</th>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>10</td>
<td>12</td>
<td class="custom">9</td>
<td>13</td>
</tr>
<tr>
<td>B</td>
<td>15</td>
<td>18</td>
<td>17</td>
<td>23</td>
</tr>
<tr>
<td>C</td>
<td>20</td>
<td class="custom">19</td>
<td>22</td>
<td>25</td>
</tr>
</tbody>
</table></body></html>

Just use whatever it is in the if that decides whether to add it or not.

https://en.xdnf.cn/q/118095.html

Related Q&A

Sort a dictionary of dictionaries python

I have a dictionary of dictionaries like the followingd = {hain: {facet: 1, wrapp: 1, chinoiserie: 1}, library: {sconc: 1, floor: 1, wall: 2, lamp: 6, desk: 1, table: 1, maine: 1} }So, I want to rever…

How can I get python generated excel document to correctly calculate array formulas

I am generating some excel files with python using python 3.6 and openpyxl.At one point I have to calculate standard deviations of a subsection of data. In excel this is done with an array formula. Wri…

Unable to locate element in Python Selenium

Im trying to locate an element using python selenium, and have the following code:zframe = driver.find_element_by_xpath("/html/frameset/frameset/frame[5]") driver.switch_to.frame(zframe) find…

How to import a variable from a different class

I have an instance of a class that i set the value to self.world inside a class named zeus inside a module named Greek_gods. and i have another class names World inside a module name World.How can i te…

Scrapy: AttributeError: YourCrawler object has no attribute parse_following_urls

I am writing a scrapy spider. I have been reading this question: Scrapy: scraping a list of links, and I can make it recognise the urls in a listpage, but I cant make it go inside the urls and save the…

initializer is not a constant, error C2099, on compiling a module written in c for python

i tried to compile a python module called distance, whith c "python setup.py install --with-c" using msvc 2017 on windows 10, i got this error ,Cdistance / distance.c (647): error C2099: init…

How can make pandas columns compare check cell?

I have a two file. a.txt has the below data.Zone,Aliase1,Aliase2 VNX7600SPB3_8B3_H1,VNX7600SPB3,8B3_H1 VNX7600SPBA_8B4_H1,VNX7600SPA3,8B4_H1 CX480SPA1_11B3_H1,CX480SPA1,11B3_H1 CX480SPB1_11B4_H1,CX480S…

Flask argument of type _RequestGlobals is not iterable

When I tried to use Flask-WTForms, I followed these steps:from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Emailclass EmailPassword…

PumpStreamHandler can capture the process output in realtime

I try to capture a python process output via apache-commons-exec. But it looks like it wont print the output, the output is only displayed after I the python process is finished.Heres my java codeComma…

Freezing a CNN tensorflow model into a .pb file

Im currently experimenting with superresolution using CNNs. To serve my model Ill need to frezze it first, into a .pb file, right? Being a newbie I dont really know how to do that. My model basically …