How can I import a dataframe from another script - python

I have a little beginner issue doing imports between scripts, maybe someone can help?
I wrote 2 Modules:
- B01_Import_CSV_V1.py
In the import script, i did load a .csv and saved it as a pandas dataframe (named "df").
import pandas as pd
global df
global df2
#%% load file via static path
if True:
tester=r'C:\local_calc\Python_DemoFiles\20220219_70788_406_02_C10_275C_Ges.csv'
df=pd.read_csv(tester, sep=';',decimal=",", skipfooter=1300, engine='python')
print ('FINISHED loading file ' + tester)
- plot.py
The plot script should process this data.
#%% Imports
import matplotlib.pyplot as plt
import B01_Import_CSV_V1 #<- this works
#from B01_Import_CSV_V1 import df #<- this does not work
#%%% plot
fig=plt.figure(figsize=(15,8))
ax=fig.add_subplot(111)
ax2=ax.twinx()
ax3=ax.twinx()
ax.plot( df['70788.1.E602000_W1:6'], c = 'b')
My questions:
It will only work, if i use the code "import B01_Import_CSV_V1" in the first script.
If I use "from B01_Import_CSV_V1 import df", it won't.
-> Why is that?
If I integrate the code of Import-Script in a main function (if name=="main": ), i learned that this code won´t be executed anymore while import.
The plot script won´t work either then.
-> Does this mean, I have to execute the csv-Import within the plot script?
Is there any way to execute scripts separately and then use the variables from each other?

Just make a function and import that in the other file:
import pandas as pd
def load_df():
tester=r'C:\local_calc\Python_DemoFiles\20220219_70788_406_02_C10_275C_Ges.csv'
df=pd.read_csv(tester, sep=';',decimal=",", skipfooter=1300, engine='python')
print ('FINISHED loading file ' + tester)
return df
Then use in the other:
from B01_Import_CSV_V1 import load_df
df = load_df()

Related

Plotly express doesn't load and refuse to connect

I have this simple program that should display a pie chart, but whenever I run the program, it opens a page on Chrome and just keeps loading without any display, and sometimes it refuses to connect. How do I solve this?
P.S: I would like to use it offline, and I'm running it using cmd on windows10
import pandas as pd
import numpy as np
from datetime import datetime
import plotly.express as px
def graph(dataframe):
figure0 = px.pie(dataframe,values=dataframe['POPULATION'],names=dataframe['CONTINENT'])
figure0.show()
df = pd.DataFrame({'POPULATION':[60,17,9,13,1],'CONTINENT':['Asia','Africa','Europe','Americas','Oceania']})
graph(df)
Disclaimer: I extracted this answer from the OPs question. Answers should not be contained in the question itself.
Answer provided by g_odim_3:
So instead of figure0.show(), I used figure0.write_html('first_figure.html', auto_open=True) and it worked:
import pandas as pd
import numpy as np
from datetime import datetime
import plotly.express as px
def graph(dataframe):
figure0 = px.pie(dataframe,values=dataframe['POPULATION'],names=dataframe['CONTINENT'],title='Global Population')
# figure0.show()
figure0.write_html('first_figure.html', auto_open=True)
df = pd.DataFrame({'POPULATION':[60,17,9,13,1],'CONTINENT':['Asia','Africa','Europe','Americas','Oceania']})
graph(df)
I'm 99% sure that this is a version issue. It's a long time since you needed an internet connection to build Plotly figures. Follow the instructions here on how to upgrade your system. I've tried your exact code on my end at it produces the following plot:
I'm on Plotly 5.2.2. Run import plotly and plotly.__version__ to check the version on your end.

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")

Is it possible to reuse import code in Python?

There are several imports that are common between some files in my project. I would like to reuse this code, concentrating it in a unique file and have just one import in the other files. Is it possible?
Or is there another way not to replicate the desired import list in multiple files?
Yes its possible. You can create a Python file with imports and then import that Python file in your code.
For Eg:
ImportFile.py
import pandas as pd
import numpy as np
import os
MainCode.py:
from ImportFile import *
#Here you can use pd,np,os and complete your code
OR
from ImportFile import pd,np
#And then use pd and np

python file does not run properly on Spyder

I am using Spyder as my python IDE.
I tried run this python code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
path = os.getcwd() + '\ex1data1.txt'
data = pd.read_csv(path, header = None, names = ['Population', 'Profit'])
data.head()
In theory it is supposed to show me a table of data since I am using
data.head()
at the end
but when I run it, it only shows :
I thought it was supposed to display a new window with the data table.
What is wrong?
You are calling data.head() in .py script. The script is supposed to only read the data, not print it. Try print(data.head())
You want to print your data.head() so do that...
print(data.head())

plot in Pandas immediately closes

I have a problem of plotting the data. I run the following python code:
import pandas as pd
df = pd.read_csv("table.csv")
values = df["blah"]
values.plot()
print 1
df['blahblah'].plot()
print 2
My output is:
50728417:Desktop evgeniy$ python test2.py
1
2
50728417:Desktop evgeniy$
And finally I see how launches python icon( picture of rocket, by the way , what is it?) in my Dock( using mac os), and then it disappears. Printed numbers 1,2 show me that no error exist. So have no idea what to do next.
The problem is that pandas's DataFrame.plot does not block. Therefore the figures are closed when your program ends. Pandas uses matplotlib internally so you can circumvent this by calling matplotlib.pyplot.show with block=True like so:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("table.csv")
values = df["blah"]
values.plot()
print 1
df['blahblah'].plot()
print 2
plt.show(block=True)
This way the program will only end when plt.show returns, which is after you closed all figures.

Categories