load workbook with openpyxl ValueError Duplicate position 0.0 - python-3.x

I'm trying to open a xlsx file in Python with openpyxl but I've this error :
raise ValueError("Duplicate position {0}".format(stop.position))
ValueError: Duplicate position 0.0
I don't understand what does it mean and I haven't found an issue explained for this error. Here is my code in file gestion_fichiers_excel :
from openpyxl import load_workbook
from openpyxl import Workbook
def loadfile():
workbook = load_workbook(filename="Feuille_decisions.xlsx")
return workbook**
def get_decisions(workbook):
num_entreprise=workbook.active["B4"].value
prix_prod1=workbook.active["B7"].value
prix_prod2=workbook.active["C7"].value
list_decisions=[num_entreprise,prix_prod1,prix_prod2]
return list_decisions
And another file which calls gestion_fichiers_excel :
import os
import tkinter as tk
import tkinter.ttk
from gestion_fichiers_excel import *
class PageDecisions(tk.Frame):
def init(self, master):
self.workbook=loadfile()
self.list_decisions=get_decisions(self.workbook)
Thanks for your help. As you can see, I'm a beginner...

I had the same issue and I found out this error was introduced in pandas version 1.2.0. Previous versions will load the file successfully.

Related

Backtrader in Python AttributeError: 'DataFrame' object has no attribute 'setenvironment'. What's the problem and how to solve it?

new to backtrader
when getting starting with the documentation and implemnting the code, i get the error
AttributeError: 'DataFrame' object has no attribute 'setenvironment' in the cerebro.adddata line
you can check in the image below:
the error when i run cerebro.adddata
i have already tried the solution mentionned in this Backtrader error: 'DataFrame' object has no attribute 'setenvironment' but nothing changed
if anyone has experienced this before and could help will be nice, this is the code i'm using and i don't know where the problem is:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])
import pandas as pd
import pandas_datareader as pdr
#import backtrader platform
import backtrader as bt
if __name__ == '__main__':
# Create a cerebro entity
cerebro = bt.Cerebro()
#create a data feed
data= pd.read_csv('EURUSD20102020')
#add the Data Feed to Cerebro
cerebro.adddata(data)
# Set our desired cash start
cerebro.broker.setcash(100000.0)
# Print out the starting conditions
print('Starting Portfolio value: %.2f' % cerebro.broker.get_value())
# Run over everything
cerebro.run()
# Print out the final result
print('Final Portfolio Value: %.2f' % cerebro.broker.get_value())

Argument error when compiling .exe from Python using PyInstaller

I am trying to write a screen recorder program in python. My code runs normally in the compiler. But when I convert it to .exe, it raises this error:
[ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (415) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): project.avi in function 'cv::icvExtractPattern'
I used pyinstaller to convert to .exe.
This is my code:
from tkinter import*
from tkinter import messagebox as msj
from PIL import ImageTk, Image
from PIL import ImageGrab
import os
import time
import cv2
import numpy as np
import glob
recording=False
i = 0
size = 100, 100
mainWindow=Tk()
mainWindow.title("ScreenRecorder")
mainWindow.geometry("200x200")
scriptDirectory = (os.path.dirname(os.path.realpath(__file__)))
def convert(imageCount):
img_array = []
for ip in range(1,imageCount):
x="snap"+str(ip)+".jpg"
for filename in glob.glob(x):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img_array.append(img)
out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 9, size)
for iz in range(len(img_array)):
out.write(img_array[iz])
out.release()
for a in range(1,imageCount+1):
os.remove("snap"+str(a)+".jpg")
def record():
global i
print(recording)
if(recording==True):
i+=1
fileName= ("snap"+str(i))
#time.sleep(0.00005)
image = ImageGrab.grab()
name=fileName+".jpg"
image.save(name,'JPEG')
imgX = (Image.open("snap"+str(i)+".jpg"))
imgX= imgX.resize(size, Image.ANTIALIAS)
imgX=ImageTk.PhotoImage(imgX)
mainWindow.after(1, record)
def startButton():
global recording
print("ehe")
recording=True
record()
def stopButton():
global recording
recording=False
record()
convert(i)
startButton=Button(text="Start",command=startButton)
startButton.pack()
stopButton=Button(text="Stop",command=stopButton)
stopButton.pack()
mainWindow.after(1, record)
mainWindow.mainloop()
I can just advise you to use another method, i think it's more simple, try to use 'auto py to exe'.This is a module that can be installed from the net or from the pip installer.
see from here.This the only way that i use for my codes.
Secondly, iknow that if the program is not opened using the format of .py will never be opened at .exe
hope i helped you.

Python module not accessible to function inside class

Code below works as expected. It prints 5 random numbers.
import numpy as np
class test_class():
def __init__(self):
self.rand_nums = self.create_rand_num()
def create_rand_num(self):
numbers = np.random.rand(5)
return numbers
myclass = test_class()
myclass.rand_nums
However, the following does not work. NameError: name 'np' is not defined
import numpy as np
from test.calc import create_rand_num
class test_class():
def __init__(self):
self.rand_nums = create_rand_num()
myclass = test_class()
myclass.rand_nums
# contents of calc.py in test folder:
def create_rand_num():
print(np.random.rand(5))
But, this works:
from test.calc import create_rand_num
class test_class():
def __init__(self):
self.rand_nums = create_rand_num()
myclass = test_class()
myclass.rand_nums
# contents of calc.py in test folder:
import numpy as np
def create_rand_num():
print(np.random.rand(5))
Why must I have 'import numpy as np' inside calc.py? I already have this import before my class definition. I am sure I am misunderstanding something here, but I was trying to follow the general rule to have all the import statements at the top of the main code.
What I find confusing is that when I say "from test.calc import create_rand_num," how does Python know whether "import numpy as np" is included at the top of calc.py or not? It must know somehow, because when I include it, the code works, but when I leave it out, the code does not work.
EDIT: After reading the response from #DeepSpace, I want to ask the following:
Suppose I have the following file.py module with contents listed as shown:
import numpy as np
import pandas as pd
import x as y
def myfunc():
pass
So, if I have another file, file1.py, and in it, I say from file.py import myfunc, do I get access to np, pd, and y? This is exactly what seems to be happening in my third example above.
In my third example, notice that np is NOT defined anywhere in the main file, it is only defined in calc.py file, and I am not importing * from calc.py, I am only importing create_rand_num. Why do I not get the same NameError error?
Python is not like C. Importing a module does not copy-paste its source. It simply adds a reference to it to the locals() "namespace". import numpy as np in one file does not make it magically available in all other files.
You have to import numpy as np in every file you want to use np.
Perhaps a worthwhile reading: https://docs.python.org/3.7/reference/simple_stmts.html#the-import-statement

Exporting a matplotlib chart directly to Excel? Without saving to file first

I am trying to write a matplotlib image directly into an Excel file using xlsx writer - ideally without saving the file to the disk.
I have found this answer: Writing pandas/matplotlib image directly into XLSX file but I cannot get it to work, especially not with Python 3.
This: wks1.insert_image(2,2, imgdata doesn't work, because:
path should be string, bytes, os.PathLike or integer, not _io.BytesIO
This: wks1.insert_image(2,2,"",{'image data': imgdata})
gives a warning
Image file '' not found.
and produces an excel file with no chart.
What does work is saving the file locally - but I'd like to understand if there's a way to avoid it.
fig.savefig('test.png', format='png')
wks1.insert_image(2,2, 'test.png')
Thoughts? The full code is:
import xlsxwriter
import numpy as np
import matplotlib.pyplot as plt
import io
x=np.linspace(-10,10,100)
y=x**2
fig,ax=plt.subplots()
ax.plot(x,y)
workbook = xlsxwriter.Workbook('test chart.xlsx')
wks1=workbook.add_worksheet('Test chart')
wks1.write(0,0,'test')
imgdata=io.BytesIO()
fig.savefig(imgdata, format='png')
wks1.insert_image(2,2,"",{'image data': imgdata})
#wks1.insert_image(2,2, imgdata)
workbook.close()
According to the documentation (and the link to the question you provided), the correct spelling for the optional argument to be passed to insert_image is image_data (noting the underscore _)
import xlsxwriter
import numpy as np
import matplotlib.pyplot as plt
import io
x=np.linspace(-10,10,100)
y=x**2
fig,ax=plt.subplots()
ax.plot(x,y)
workbook = xlsxwriter.Workbook('test chart.xlsx')
wks1=workbook.add_worksheet('Test chart')
wks1.write(0,0,'test')
imgdata=io.BytesIO()
fig.savefig(imgdata, format='png')
wks1.insert_image(2,2, '', {'image_data': imgdata})
workbook.close()

python bokeh error with output_file in class

I have a probleme using bokeh in a class.
The following code is runing when i use the object "Graph" in the same file (.py), but not when i'm calling the class from an other file, and i don't know why.
class Graph():
import pandas as pd
from bokeh.models import HoverTool
from bokeh.plotting import figure, show, output_file, ColumnDataSource
def __init__(self, df, indicators=None):
self.df = df
self.output_file("test.html" , title='test')
....
I have the following error:
TypeError: output_file() got multiple values for argument 'title'
Does anybody know how can I fix it?
For information, the following code:
class Graph():
import pandas as pd
from bokeh.models import HoverTool
from bokeh.plotting import figure, show, output_file, ColumnDataSource
def __init__(self, df, indicators=None):
self.df = df
self.output_file("test.html")
....
returns:
Traceback (most recent call last):
File "Documents/Programmation/python/Trade/Indicators.py", line 50, in <module>
a = TradeGraph(df)
File "/Users/Alex/Documents/Programmation/python/Graph.py", line 29, in __init__
self.output_file("test.html")
File "/anaconda3/lib/python3.6/site-packages/bokeh/io/output.py", line 77, in output_file
root_dir=root_dir
File "/anaconda3/lib/python3.6/site-packages/bokeh/io/state.py", line 166, in output_file
if os.path.isfile(filename):
File "/anaconda3/lib/python3.6/genericpath.py", line 30, in isfile
st = os.stat(path)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not Graph
and the following code:
class Graph():
import pandas as pd
from bokeh.models import HoverTool
from bokeh.plotting import figure, show, output_file, ColumnDataSource
def __init__(self, df, indicators=None):
self.df = df
self.output_file()
....
returns the same (last) error.
Thanks
You have evidently defined a method output_file on your own class, and that is where the problem is. (As an aside, please always try to ask questions with complete minimal code). Based on the output above, the most likely explanation is that you have forgotten to add the self parameter that Python methods should always have. That is, you have something like:
class Graph(object):
def output_file(title):
when you need something like:
class Graph(object):
def output_file(self, title):
However, I would question the value of having an output_file method at all. Unless you are doing something out of the ordinary, you should just call Bokeh's output_file function directly. However, please also note that output_file activates a persistent implicit mode. That is useful especially in interactive environments, but may not be in a program that saves lots of things. There is also a save function that just gives you explicit control wherever you want to perform a save.
Thank you for you answer,
I finnaly import each need module in each methode.
I thought i could all import them one time beteween the class definition and the class initialisation, but doesn't work,
Thanks

Resources