Home > Blockchain >  How to create a conditionnal column that carry the URL of a dataframe using Pandas
How to create a conditionnal column that carry the URL of a dataframe using Pandas

Time:08-18

I'm trying to make a conditionnal column using enter image description here

The problem with the code above is that the hyperlink Click here, gives a csv with the hole dataframe (including the three rows).

Do you know how to fix that ? Do you have any suggestions, please ?

CodePudding user response:

here is one way to do it

df['URL'] = df.apply(lambda x: f"<a href=\"https://{x['Community_name']}.com/\">{x['Community_name']}</a>", axis=1)


OR, without the use of apply

df['URL'] = "<a href=\"https://"   df['Community_name']   ".com/\">"   df['Community_name']   "</a>"
df
    Community       URL
0   StackOverflow   <a href="https://StackOverflow.com/">StackOver...
1   GISExchange     <a href="https://GISExchange.com/">GISExchange...
2   DBAExchange     <a href="https://DBAExchange.com/">DBAExchange...

CodePudding user response:

After some struggling, I end up with the code below that answer my question.

I first created a function that decode the csv and so I can filter the dataframe.
Then, replaced the .apply method with a for loop.

import pandas as pd
from IPython.display import HTML
import base64

df = pd.DataFrame({'Community': ['StackOverflow','GISExchange', 'DBAExchange']})

df.insert(1, "URL", 'Click here')

def pyld(val):
    csv = df[df['Community']==val]['Community'].to_csv(index=False)
    b64 = base64.b64encode(csv.encode())
    payload = b64.decode()
    return payload

for i, row in df.iterrows():
    row['URL'] = f'<a download="data.csv" href="data:text/csv;base64,{pyld(df["Community"][i])}" target="_blank">Click here</a>'

>>> HTML(df.to_html(escape=False))

enter image description here

  • Related