How to convert a pandas plot into an image - python

I am working on an app which will be able to show a graph of the company's performance in stocks, I wanted to turn the pandas plot of that company into an image without saving it. Can someone tell me what to do?
from fastquant import get_pse_data
import matplotlib.pyplot as plt
import pandas as pd
df = get_pse_data(symbol, '2019-01-01', '2020-01-01')
ma30 = df.close.rolling(30).mean()
close_ma30 = pd.concat([df.close, ma30], axis=1).dropna()
I am actually thinking of adding this plot derived from a pandas dataframe close_ma30 = pd.concat([df.close, ma30], axis=1).dropna() into my html code:
I want to create a python function that will allow me to return it as an image for a django code. Thank you for the help!

You can use Dataframe-image to convert a pandas plot into a image, you can Visit https://pypi.org/project/dataframe-image/.
dataframe_image has the ability to export both normal and styled DataFrames as images from within a Python script. Pass your normal or styled DataFrame to the export function along with a file location to save it as an image.
>>> import dataframe_image as dfi
>>> dfi.export(df_styled, 'df_styled.png')
You may also export directly from the DataFrame or styled DataFrame using the dfi.export and export_png methods, respectively.
>>> df.dfi.export('df.png')
>>> df_styled.export_png('df_styled.png)
As a Python Library
Dataframe_image can also be used outside of the notebook as a normal Python library. In a separate Python script, import the dataframe_image package and pass the file name of your notebook to the convert function.
>>> import dataframe_image as dfi
>>> dfi.convert('path/to/your_notebook.ipynb',
to='pdf',
use='latex',
center_df=True,
max_rows=30,
max_cols=10,
execute=False,
save_notebook=False,
limit=None,
document_name=None,
table_conversion='chrome'
chrome_path=None,
latex_command=None,
output_dir=None,
)
By default, the new file(s) will be saved in the same directory where the notebook resides. Do not run this command within the same notebook that is being converted.
From the Command Line
The command line tool dataframe_image will be available upon installation with the same options as the convert function from above.
dataframe_image --to=pdf "my notebook with dataframes.ipynb"
Finding Google Chrome
You must have Google Chrome (or Brave) installed in order for dataframe_image to work. The path to Chrome should automatically be found. If Chrome is not in a standard location, set it with the chrome_path parameter.
Using matplotlib instead of Chrome
If you do not have Chrome installed or cannot get it to work properly, you can alternatively use matplotlib to convert the DataFrames to images. Select this option by setting the table_conversion parameter to 'matplotlib'.
Publish to Medium
Closely related to this package is jupyter_to_medium, which publishes your notebooks directly and quickly as Medium blog posts.
Dependencies
You must have the following Python libraries installed.

Related

Can't run Python visual element in Power BI

I'm trying to create a hist plot in Power BI.
I got installed ANaconda, MS Vusial Code.
Screenshots with my settings:
I'm trying make hist with simple table with 1 column.
The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script:
dataset = pandas.DataFrame(reg_min_ses_dt)
dataset = dataset.drop_duplicates()
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.histplot(data=dataset['reg_min_ses_dt'])
plt.show()
But I get this error:
I think, I just didn't set up some python extension or something else.
I just want make Python visual like this.
You need to activate conda before you can use its packages in PBIDesktop.exe. Simple as that.

Unable to view dataframes in Spyder's variable explorer "Can't get attribute '_unpickle_block' on"

I'm using Python 3.8.13 and Pandas 1.4.1 on Spyder 4.1.5.
I have no problem reading the dataframe into memory, but when I try to open the dataframe for viewing in the variable explorer I get the following:
"Spyder was unable to retrieve the value of this variable from the console. The error message was: Can't get attribute '_unpickle_block' on".
This is regardless of size (e.g. if I create a variable containing just the head of the dataset, the issue persists). Not sure why this specific error is showing as I don't believe I'm using a pickled object at any point.
I've confirmed that I can open the dataframe when using a Python 3.9 env with Spyder 5.1.5, but I need to use the former specs given they're locked in on a virtual machine. Here's my code as of now (very straightforward):
import pandas as pd
import numpy as np
filepath = "../../../projects2/"
df = pd.read_parquet(filepath + "hmda/lar/parquet/hmda_lar_2017.parquet")

How do I save the table generated by pandas.read_csv?

I created a csv file and used pandas.read_csv in order to access it. I used
euler_tens = pd.read_csv(filename)
and you can see that this table displays when I simply run the variable name. How do I simply save this image as a png file? This table is exactly what I needed, but now I can't seem to get that image, and I don't want to just screenshot it.
You can try with dataframe-image module
pip install dataframe-image
Example:
import pandas as pd
import dataframe_image as dfi
euler_tens = pd.read_csv(filename)
dfi.export(euler_tens, 'dataframe.png')

Is this the correct way to open a .csv file in Python?

I've so many different ways and it is still saying file not found
I'm running the code in a Jupyter Notebook.
I'd rather run the file from wherever it is. Here is the infomation for its location
Have I generated the correct code (below is the code).
import numpy
numpy.loadtxt(fname='C:\Desktop\swc-python\data\inflammation-01.csv', delimiter=',')
Also tried this but it did not work:
import numpy
numpy.fname = ('C:\Desktop\swc-python\data\small-01.csv')
openfname = open(fname,'r')
Also, an you save a Jupyter notebook in the same directory as the infomation.
these are some examples with pandas, and os, maybe they could help
they use slash, not backward slash (this option, or the option below)
# import pandas as pd
pd.read_csv("C:/Users/<Insert your user>/Desktop/code/Exercise Files/us_baby_names.csv")
or
(option below), change the current directory,
# import os and pandas library
import os
import pandas as pd
# show current working directory, change it, show it again
os.getcwd()
os.chdir('C:/Users/<Insert your user>/Desktop/code/Exercise Files/')
os.getcwd()
pd.read_csv("us_baby_names.csv")

Python Jupyter Notebook - Unable to open CSV file through a path

I am a little new to Python, and I have been using the Jupyter Notebook through Anaconda. I am trying to import a csv file to make a DataFrame, but I am unable to import the file.
Here is an attempt using the local method:
df = pd.read_csv('Workbook1')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-11-a2deb4e316ab> in <module>()
----> 1 df = pd.read_csv('Workbook1')
After that I tried using the path (I put user for my username)
df = pd.read_csv('Users/user/Desktop/Workbook1.csv')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-13-3f2bedd6c4de> in <module>()
----> 1 df = pd.read_csv('Users/user/Desktop/Workbook1.csv')
I am using a Mac, which I am also new to, and I am not 100% sure if I am correctly importing the right path. Can anyone offer some insight or solutions that would allow me to open this csv file.
Instead of providing path, you can set a path using the code below:
import os
import pandas as pd
os.chdir("D:/dataset")
data = pd.read_csv("workbook1.csv")
This will surely work.
Are you sure that the file exists in the location you are specifying to the pandas read_csv method? You can check using the os python built in module:
import os
os.path.isfile('/Users/user/Desktop/Workbook1.csv')
Another way of checking if the file of interest is in the current working directory within a Jupyter notebook is by running ls -l within a cell:
ls -l
I think the problem is probably in the location of the file:
df1 = pd.read_csv('C:/Users/owner/Desktop/contacts.csv')
Having done that, now you can play around with the big file if you have, and create useful data with:
df1.head()
The OS module in python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules.
import os
import pandas as pd
os.chdir("c:\Pandas")
df=pd.read_csv("names.csv")
df
This might help. :)
The file name is case sensitive, so check your case.
I had the same problem on a Mac too and for some reason it only happened to me there. And I tried to use many tricks but nothing works. I recommend you go directly to the file, right click and then press “alt” key after that the option to “copy route” will appear, and just paste it into your jupyter. For some reason that worked to me.
I believe the issue is that you're not using fully qualified paths. Try this:
Move the data into a suitable project directory. You can do this using the %%bash Magic commands.
%%bash
mkdir -p /project/data/
cp data.csv /project/data/data.csv
You can read the file
f = open("/project/data/data.csv","r")
print(f.read())
f.close()
But it might be most useful to load it into a library.
import pandas as pd
data = pd.read_csv("/project/data/data.csv")
I’ve created a runnable Jupyter notebook with more details here: Jupyter Basics: Reading Files.
Try double quotes, instead of single quotes. it worked for me.
you can open csv files in Jupyter notebook by following these easy steps-
Step 1 - create a directory or folder (you can also use old created folder)
Step 2 - Change your Jupyter working directory to that created directory -
import os
os.chdir('D:/datascience/csvfiles')
Step 3 - Now your directory is changed in Jupyter Notebook. Store your file(s) in that directory.
Step 4 - Open your file -
import pandas as pd
df = pd.read_csv("workbook1.csv")
Now your file is read and stored in a Data Frame variable df, you can display this file content by following
df.head() - display first five rows of this file
df - display all rows of this file
Happy Data Science!
There was a similar problem for me while reading a CSV file in Jupyter notebook from the computer.
I solved it by substituting the "" symbol with "/" in the path like this.
This is what I had:
"C:\Users\RAJ\Desktop\HRPrediction\HRprediction.csv"
This is what I changed it for:
"C:/Users/RAJ/Desktop/HRPrediction/HRprediction.csv".
This is what worked for me. I am using Mac OS.
Save your CSV on a separate folder on your desktop.
When opening a Jupyter notebook press on the same folder that your dataset is currently saved in. Press new notebook in the upper right hand corner.
After opening a new notebook. Code as per usual and read your data using import pandas as pd and pd.read_csv calling to your dataset.
 No need to use anything extra just use r in front of the location.
df = pd.read_csv(r'C:/Users/owner/Desktop/contacts.csv'

Categories