PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 27, 2022

[FIXED] How to add a hyperlink for downloading a dataframe as csv using Pandas

 August 27, 2022     csv, dataframe, pandas, python, streamlit     No comments   

Issue

I'm working with a .csv cars dataset (that I got from here) and I'm trying to:

  1. Convert this .csv to a pandas dataframe (Done, see df)
  2. Group the dataframe by cars models (Done, see grouped_df)
  3. Make a column with a hyperlink to download the .csv/df for each car in the grouped_df (To be finalized)

CODE :

import pandas as pd
from IPython.display import HTML

df = pd.read_csv("cars.csv", delimiter=';', skiprows=[1])

display(df.head(5))

grouped_df = df.groupby('Car').agg(NumberOfCars=('Car', 'size'), 
                                   MeanOfWeight=('Weight', 'mean'),
                                   MeanOfAcceleration=('Acceleration', 'mean'))

grouped_df.insert(len(grouped_df.columns), "DownloadCsv", 'Download the details (.csv)')

grouped_df['DownloadCsv'] = grouped_df['DownloadCsv'].apply(lambda x: f'<a href="https://stackoverflow.com/{x}">{x}</a>')

HTML(grouped_df.sample(5).to_html(escape=False))

>>> display(df.head(5))

enter image description here

>>> HTML(grouped_df.sample(5).to_html(escape=False))

enter image description here

For example, if the user click on "Download the details (.csv)" of the second row, he should get a .csv of all rows in df where the column car equals to "Ford Torino 500".

By the way, the code will be implemented in a streamlit app.

Is there any way to achieve this ? Do you have any propositions, please ?

EDIT :

By following furas's brilliant suggestion, I came up with this code :

csv = df.to_csv(index=False, sep=';')
b64 = base64.b64encode(csv.encode())
payload = b64.decode()

grouped_df['DownloadCsv'] = grouped_df['DownloadCsv'].apply(
    lambda x: f'<a download="{x}.csv" href="data:text/csv;base64,{payload}" target="_blank">{x}</a>')

st.write(HTML(grouped_df.sample(5).to_html(escape=False)), unsafe_allow_html=True)

enter image description here


Solution

In this post, I explain how I managed to filter the dataframe/csv downloaded.

Note = I don't know why yet but the type of all the columns has to be string

So I needed to add this :

df_columns = list(grouped_df)  # Creates list of all column headers
grouped_df[all_columns] = grouped_df[all_columns].astype(str)


Answered By - L'Artiste
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing