I have a problem with writing to my excel file - python-3.x

I am getting error message when im trying to write to my excel file.
On this line: df_Percent_Change.to_excel(writer, sheet_name=x, startcol=8)
Traceback (most recent call last):
File "/Users/david.soderstrom/Dropbox (Diagona)/DS/Python/Byggmarknad_index/Byggmarknad_index.py", line 125, in
df_Percent_Change.to_excel(writer, sheet_name=x, startcol=8)
File "/Users/david.soderstrom/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 1766, in to_excel
engine=engine)
File "/Users/david.soderstrom/anaconda3/lib/python3.6/site-packages/pandas/io/formats/excel.py", line 652, in write
freeze_panes=freeze_panes)
File "/Users/david.soderstrom/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 1742, in write_cells
wks = self.book.add_worksheet(sheet_name)
File "/Users/david.soderstrom/anaconda3/lib/python3.6/site-packages/xlsxwriter/workbook.py", line 179, in add_worksheet
return self._add_sheet(name, worksheet_class=worksheet_class)
File "/Users/david.soderstrom/anaconda3/lib/python3.6/site-packages/xlsxwriter/workbook.py", line 666, in _add_sheet
name = self._check_sheetname(name, isinstance(worksheet, Chartsheet))
File "/Users/david.soderstrom/anaconda3/lib/python3.6/site-packages/xlsxwriter/workbook.py", line 717, in _check_sheetname
if len(sheetname) > 31:
TypeError: object of type 'int' has no len()
Exception ignored in: >
Traceback (most recent call last):
File "/Users/david.soderstrom/anaconda3/lib/python3.6/site-packages/xlsxwriter/workbook.py", line 154, in del
Exception: Exception caught in workbook destructor. Explicit close() may be required for workbook.
# Calculate and save the percent change for each asset
if 'Percent_Change' not in excel_db.columns:
print('Percent_Change does not exist in excel file.')
print('Calculating...')
# Loop through and read each sheet
x = 0
for x in range(countSheets):
# Read in data for the calculation
data = pd.read_excel('databas.xlsx', sheet_name=x, index_col='Date')
# Calculate the percent change from day to day
Percent_Change = data['Adj Close'].pct_change()*100
print(type(Percent_Change))
df_Percent_Change = pd.DataFrame(Percent_Change)
print(type(df_Percent_Change))
writer = pd.ExcelWriter('databas.xlsx', engine='xlsxwriter')
df_Percent_Change.to_excel(writer, sheet_name=x, startcol=8)
# Save the result
writer.save()
writer.close()
x += 1

Related

Openpyxl recognize data: TypeError: 'method' object is not subscriptable and is not a valid coordinate or range error

I'm new to openpyxl. I need to copy several columns from a file and paste it on another file, with the same columns.
I'm starting my code, but getting an error:
file1 = load_workbook('PRODUCTION.xlsx') ws = file1.active column = ws.cell['ID'] print (column)
I get this error:
Traceback (most recent call last): File "c:\Users\Ana\Documents\PRODUCTION Project\production.py", line 29, in <module> column = ws.cell['ID'] TypeError: 'method' object is not subscriptable
And when I tried only column = ws ['ID']
I get:
Traceback (most recent call last): File "c:\Users\Ana\Documents\PRODUCTION Project\production.py", line 29, in <module> column = ws ['ID'] File "C:\Users\Ana\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\worksheet\worksheet.py", line 290, in __getitem__ min_col, min_row, max_col, max_row = range_boundaries(key) File "C:\Users\Ana\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\utils\cell.py", line 135, in range_boundaries raise ValueError(msg) ValueError: ID is not a valid coordinate or range PS C:\Users\Ana\Documents\PRODUCTION Project>
Thanks in advance.

division by zero when population size is 1 neat-python

Note: I submitted an issue on their GitHub, but looking at their GitHub, but it does not look like anyone will reply based on other issues submitted.
File "C:\Users\hunty\AppData\Local\RLBotGUIX\venv\lib\site-packages\neat\math_util.py", line 9, in mean
return sum(map(float, values)) / len(values)
ZeroDivisionError: division by zero
When the population size of my model is set to 1, I receive a division by 0 error, when set to a number > 1, I don't get the error. I found a stack overflow page relating to this, but there was no solution.
Here is some of my code:
config file (the portion that matters):
[NEAT]
fitness_criterion = max
fitness_threshold = 9999
pop_size = 2
reset_on_extinction = False
eval/fitness function:
def main(gnomes, config):
global net, ge
net = neat.nn.FeedForwardNetwork(gnomes[0], config)
ge = gnomes[0]
ge.fitness = 0
If you have a solution or need more code, please say so!
Whole Traceback:
****** Running generation 0 ******
Process Process-1:
Traceback (most recent call last):
File "C:\Users\hunty\AppData\Local\RLBotGUIX\Python37\lib\multiprocessing\process.py", line 297, in _bootstrap
self.run()
File "C:\Users\hunty\AppData\Local\RLBotGUIX\Python37\lib\multiprocessing\process.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\hunty\AppData\Local\RLBotGUIX\venv\lib\site-packages\rlbot\setup_manager.py", line 655, in run_agent
bm.run()
File "C:\Users\hunty\AppData\Local\RLBotGUIX\venv\lib\site-packages\rlbot\botmanager\bot_manager.py", line 196, in run
self.load_agent()
File "C:\Users\hunty\AppData\Local\RLBotGUIX\venv\lib\site-packages\rlbot\botmanager\bot_manager.py", line 117, in load_agent
self.agent = agent_class(self.name, self.team, self.index)
File "C:\Users\hunty\AppData\Local\RLBotGUIX\MyBots\learnie\src\bot.py", line 40, in __init__
run(config_path)
File "C:\Users\hunty\AppData\Local\RLBotGUIX\MyBots\learnie\src\bot.py", line 30, in run
winner = p.run(main)
File "C:\Users\hunty\AppData\Local\RLBotGUIX\venv\lib\site-packages\neat\population.py", line 89, in run
fitness_function(list(iteritems(self.population)), self.config)
File "C:\Users\hunty\AppData\Local\RLBotGUIX\MyBots\learnie\src\bot.py", line 18, in main
net = neat.nn.FeedForwardNetwork(gnomes[0], config)
TypeError: __init__() missing 1 required positional argument: 'node_evals'
uninitialized_bot error reading header: An existing connection was forcibly closed by the remote host

Constant error when using ImageMagick with Python

When I did a code to convert PDF files to JPG images, but I have met an issue.Sometimes the .pdf file work well.But sometimes there is an error,the first temp file can't read.I checked the temp folder.When it works well, all the created temp file be deleted successfully. And when the error happens,only the first temp file is deleted. I can't resolve it.Anyone can fix?
code:
from wand.image import Image
with open("C:\software\1234.pdf",'rb') as f:
image_binary = f.read()
f.close()
with Image(blob=image_binary,resolution=400) as img:
Traceback (most recent call last):
File "C:\xxxx\eclipse-workspace\test\123\pdf2jpg.py", line 16, in
with Image(blob=image_binary,resolution=400) as img:
File "C:\xxxx\AppData\Local\Programs\Python\Python37\lib\site-packages\wand\image.py", line 2742, in init
self.read(blob=blob, resolution=resolution)
File "C:\xxxx\AppData\Local\Programs\Python\Python37\lib\site-packages\wand\image.py", line 2822, in read
self.raise_exception()
File "C:\xxxx\AppData\Local\Programs\Python\Python37\lib\site-packages\wand\resource.py", line 222, in raise_exception
raise e
wand.exceptions.CorruptImageError: unable to read image data `C:/xxxx/AppData/Local/Temp/magick-22200zyw89Zpq8IFJ1' # error/pnm.c/ReadPNMImage/1344
Exception ignored in:
Traceback (most recent call last):
File "C:\xxxx\AppData\Local\Programs\Python\Python37\lib\site-packages\wand\resource.py", line 232, in del
File "C:\xxxx\AppData\Local\Programs\Python\Python37\lib\site-packages\wand\image.py", line 2767, in destroy
TypeError: object of type 'NoneType' has no len()

openpyxl 'TypeError: expected <class 'int'>'

Python 3.6 Newest openpyxl
So, I'm working with an excel using openpyxl. I have a very boring test.xlsx excel, which I can read with the following code:
import os
import openpyxl
wb = openpyxl.load_workbook('test.xlsx')
sheet = wb['Sheet1']
print(sheet)
However, when I change to a fairly complex excel document 'apqptest.xlsx.'
import os
import openpyxl
wb = openpyxl.load_workbook('apqptest.xlsx')
sheet = wb['Sheet1']
print(sheet)
I get the following error (I have created the same sheet1 on the apqptest.xlsx document just fyi):
C:\Users\nkent\PycharmProjects\webscraper\venv\Scripts\python.exe "C:/Users/nkent/Desktop/Programs/Quote Preperation.py"
Traceback (most recent call last):
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\descriptors\base.py", line 57, in _convert
value = expected_type(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/nkent/Desktop/Programs/Quote Preperation.py", line 3, in <module>
wb = openpyxl.load_workbook('apqptest.xlsx')
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\reader\excel.py", line 274, in load_workbook
for c in find_charts(archive, rel.target):
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\chart\reader.py", line 43, in find_charts
drawing = SpreadsheetDrawing.from_tree(tree)
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 84, in from_tree
obj = desc.expected_type.from_tree(el)
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 84, in from_tree
obj = desc.expected_type.from_tree(el)
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 84, in from_tree
obj = desc.expected_type.from_tree(el)
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 100, in from_tree
return cls(**attrib)
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\drawing\graphic.py", line 53, in __init__
self.rot = rot
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\descriptors\base.py", line 69, in __set__
value = _convert(self.expected_type, value)
File "C:\Users\nkent\PycharmProjects\webscraper\venv\lib\site-packages\openpyxl\descriptors\base.py", line 59, in _convert
raise TypeError('expected ' + str(expected_type))
TypeError: expected <class 'int'>

Optional user input with timeout for Python 3

I am trying to make a code that will ask for a user input and if that input is not given in a set amount of time will assume a default value and continue through the rest of the code without requiring the user to hit enter. I am running in Python 3.5.1 on Windows 10.
I have looked through: Keyboard input with timeout in Python, How to set time limit on raw_input, Timeout on a function call, and Python 3 Timed Input black boxing the answers but none of the answers are suitable as they are not usable on Windows (principally use of signal.SIGALRM which is only available on linux), or require a user to hit enter in order to exit the input.
Based upon the above answers however i have attempted to scrap together a solution using multiprocessing which (as i think it should work) creates one process to ask for the input and creates another process to terminate the first process after the timeout period.
import multiprocessing
from time import time,sleep
def wait(secs):
if secs == 0:
return
end = time()+secs
current = time()
while end>current:
current = time()
sleep(.1)
return
def delay_terminate_process(process,delay):
wait(delay)
process.terminate()
process.join()
def ask_input(prompt,term_queue,out_queue):
command = input(prompt)
process = term_queue.get()
process.terminate()
process.join()
out_queue.put(command)
##### this doesn't even remotly work.....
def input_with_timeout(prompt,timeout=15.0):
print(prompt)
astring = 'no input'
out_queue = multiprocessing.Queue()
term_queue = multiprocessing.Queue()
worker1 = multiprocessing.Process(target=ask_input,args=(prompt,term_queue,out_queue))
worker2 = multiprocessing.Process(target=delay_terminate_process,args=(worker1,timeout))
worker1.daemon = True
worker2.daemon = True
term_queue.put(worker2)
print('Through overhead')
if __name__ == '__main__':
print('I am in if statement')
worker2.start()
worker1.start()
astring = out_queue.get()
else:
print('I have no clue what happened that would cause this to print....')
return
print('returning')
return astring
please = input_with_timeout('Does this work?',timeout=10)
But this fails miserably and yields:
Does this work?
Through overhead
I am in if statement
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj)
File "C:\Anaconda3\lib\multiprocessing\reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 58, in __getstate__
context.assert_spawning(self)
File "C:\Anaconda3\lib\multiprocessing\context.py", line 347, in assert_spawning
' through inheritance' % type(obj).__name__
RuntimeError: Queue objects should only be shared between processes through inheritance
Does this work?
Through overhead
I have no clue what happened that would cause this to print....
Does this work?Process Process-1:
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj)
File "C:\Anaconda3\lib\multiprocessing\reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
File "C:\Anaconda3\lib\multiprocessing\process.py", line 287, in __reduce__
'Pickling an AuthenticationString object is '
TypeError: Pickling an AuthenticationString object is disallowed for security reasons
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\process.py", line 254, in _bootstrap
self.run()
File "C:\Anaconda3\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:\Anaconda3\saved_programs\a_open_file4.py", line 20, in ask_input
command = input(prompt)
EOFError: EOF when reading a line
Does this work?
Through overhead
I have no clue what happened that would cause this to print....
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj)
File "C:\Anaconda3\lib\multiprocessing\reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 58, in __getstate__
context.assert_spawning(self)
File "C:\Anaconda3\lib\multiprocessing\context.py", line 347, in assert_spawning
' through inheritance' % type(obj).__name__
RuntimeError: Queue objects should only be shared between processes through inheritance
Process Process-2:
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\process.py", line 254, in _bootstrap
self.run()
File "C:\Anaconda3\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:\Anaconda3\saved_programs\a_open_file4.py", line 16, in delay_terminate_process
process.terminate()
File "C:\Anaconda3\lib\multiprocessing\process.py", line 113, in terminate
self._popen.terminate()
AttributeError: 'NoneType' object has no attribute 'terminate'
I really don't understand the multiprocessing module well and although I have read the official docs am unsure why this error occurred or why it appears to have ran through the function call 3 times in the process. Any help on how to either resolve the error or achieve an optional user input in a cleaner manner will be much appreciated by a noob programmer. Thanks!

Resources