Home > Mobile >  Formating string value in dataframe to convert it to html tag
Formating string value in dataframe to convert it to html tag

Time:11-20

I would like to format every string value in a pandas dataframe column. I was looking in other posts and I found something like:

df['Col']=df['Col'].map('${:,.2f}'.format)

Let's say the value of every row in that column is "Hello". Example:

A  B
1  "Hello"
2  "Hello"

The final output of every row would be:

f"<br> <a href={"Hello"} title= Link; style='background-color: orange'> Title </a> </br>"

A  B
1  "f"<br> <a href={"Hello"} title= Link; style='background-color: orange'> Title </a> </br>""
2  "f"<br> <a href={"Hello"} title= Link; style='background-color: orange'> Title </a> </br>""

CodePudding user response:

df["Col"].apply(lambda s: f"<br> <a href={s} title= Link; style='background-color: orange'> Title </a> </br>""

CodePudding user response:

If you do not need to build HTML objects with many or complex conditional statements you can use a string Template via the standard library.

Create a sample dataframe with two columns, id and url.

 df1 = pd.DataFrame([[1, "google.com"],[1, "bing.com"],[1, "duckduckgo.com"]], columns=['id', 'url'])

Write a simple function that returns a template with values substituted. This will allow you to add validation, error handling, etc while processing the values.

from string import Template
def value_to_html(value):
        t = Template('<br> <a href=$url title= Link; style="background-color: orange"> Title </a> </br>')
        return t.substitute(url=value)

Then use Pandas apply() method to run the function for each row in the data frame. Remember, DO NOT MODIFY THE OBJECT YOU ARE ITERATING OVER. So best to add a new column to the dataframe.

df1['html'] = df1['url'].apply(lambda x: value_to_html(x)) 

Templating can get much more complex and if your application requires more control, check out the python wiki for more guidance.

  • Related