Issue
I'm working with a .csv
cars dataset (that I got from here) and I'm trying to:
- Convert this
.csv
to a pandas dataframe (Done, see df) - Group the dataframe by cars models (Done, see grouped_df)
- Make a column with a hyperlink to download the
.csv/df
for each car in thegrouped_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))
>>> HTML(grouped_df.sample(5).to_html(escape=False))
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)
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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.