Creating and using Excel with multiple sheets in Python - python

I am creating an Excel file with two sheets from 2 different data frames. Here is a sample code:
import pandas as pd
import openpyxl
import xlsxwriter
with pd.ExcelWriter('output.xlsx',engine='xlsxwriter') as wr:
df1.to_excel(wr, sheet_name='Final',index=False)
df2.to_excel(wr, sheet_name='Tie_Line_Data',index=False)
When I run it in any Python IDE, it runs perfectly. However, when I run it in Terminal, it gives the following error:
Traceback (most recent call last):
File "/home/memiit/public_html/Pooja_MemiIT_Server/weather_demand_data_automated_mail.py", line 382, in <module>
with pd.ExcelWriter('output.xlsx',engine='xlsxwriter') as wr:
File "/home/memiit/public_html/python3/lib/python3.6/site-packages/pandas/io/excel/_xlsxwriter.py", line 187, in __init__
self.book = xlsxwriter.Workbook(path, **engine_kwargs)
AttributeError: module 'xlsxwriter' has no attribute 'Workbook'
How do I solve this, or is there any alternative way of doing it.

Related

NameError: name 'find_stack_level' is not defined when trying to get an xlsx file from a website

I was trying to import a xlsx file from a website using the
requests
packaged and it returned me an strange error. The code and the error below.
import numpy as np
import matplotlib as plt
import pandas as pd
from io import BytesIO
import requests as rq
url = "http://pdet.mte.gov.br/images/Novo_CAGED/Jan2022/3-tabelas.xlsx"
data = rq.get(url).content
caged = pd.read_excel(BytesIO(data))
Traceback (most recent call last):
File "D:\Perfil\Desktop\UFV\trabalho_econometria.py", line 9, in <module>
caged = pd.read_excel(BytesIO(data))
File "C:\Users\Windows\anaconda3\lib\site-packages\pandas\util\_decorators.py", line 299, in wrapper
return func(*args, **kwargs)
File "C:\Users\Windows\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 344, in read_excel
data = io.parse(
File "C:\Users\Windows\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 1170, in parse
return self._reader.parse(
File "C:\Users\Windows\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 504, in parse
if header is not None and is_list_like(header):
NameError: name 'find_stack_level' is not defined
Was trying to read an xlsx sheet from a website and got a strange error.

AttributeError: partially initialized module x has no attribute y (most likely due to a circular import)

I want to use pandas to process a csv file. The main job is to duplicate a column, so I name the script file as copy.py.
import pandas as pd
df = pd.read_csv('latex.csv')
However, when I execute the file, it gets the error
$ python copy.py
Traceback (most recent call last):
File "~/sourcecode/rime-math/copy.py", line 1, in <module>
import pandas as pd
import pandas as pd
File "~/.local/lib/python3.10/site-packages/pandas/__init__.py", line 50, in <module>
from pandas.core.api import (
File "~/.local/lib/python3.10/site-packages/pandas/core/api.py", line 48, in <module>
from pandas.core.groupby import (
File "~/.local/lib/python3.10/site-packages/pandas/core/groupby/__init__.py", line 1, in <module>
from pandas.core.groupby.generic import (
File "~/.local/lib/python3.10/site-packages/pandas/core/groupby/generic.py", line 73, in <module>
from pandas.core.frame import DataFrame
File "~/.local/lib/python3.10/site-packages/pandas/core/frame.py", line 129, in <module>
from pandas.core import (
File "~/.local/lib/python3.10/site-packages/pandas/core/generic.py", line 122, in <module>
from pandas.core.describe import describe_ndframe
File "~/.local/lib/python3.10/site-packages/pandas/core/describe.py", line 37, in <module>
from pandas.core.reshape.concat import concat
File "~/.local/lib/python3.10/site-packages/pandas/core/reshape/concat.py", line 45, in <module>
from pandas.core.internals import concatenate_managers
File "~/.local/lib/python3.10/site-packages/pandas/core/internals/__init__.py", line 17, in <module>
from pandas.core.internals.concat import concatenate_managers
File "~/.local/lib/python3.10/site-packages/pandas/core/internals/concat.py", line 3, in <module>
import copy
File "~/sourcecode/rime-math/copy.py", line 4, in <module>
df = pd.read_csv('latex.csv')
AttributeError: partially initialized module 'pandas' has no attribute 'read_csv' (most likely due to a circular import)
The problem is that the name of your script file is collision with the file one of your module wants to import.
Put attention on the last 5 lines of the traceback since it is near line where error occurs:
File "~/.local/lib/python3.10/site-packages/pandas/core/internals/concat.py", line 3, in <module>
import copy
File "~/sourcecode/rime-math/copy.py", line 4, in <module>
df = pd.read_csv('latex.csv')
AttributeError: partially initialized module 'pandas' has no attribute 'read_csv' (most likely due to a circular import)
Look at the first 2 lines, it means pandas module need to import copy module at somewhere.
According to The Module Search Path, Python interpreter will search copy module in built-in modules, current directory, PYTHONPATH etc. in order.
Apparently there is no built-in modules named copy in Python, so the interpreter will then look at the files under current directory and find there is copy.py.
The content of copy.py is just one line: df = pd.read_csv(). It means we need to use pandas module. However, we are just on the way importing pandas. Pandas here is only partially initialized, that's why you see that information in backtrace.
To solve this is easy, rename the script file copy.py to some others is ok.

Pandas ExcelWriter yields AttributeError

While trying to create an xlsx file with pandas, I receive the following error:
Traceback (most recent call last):
File "<ipython-input-24-201aac2da411>", line 1, in <module>
writer = pd.ExcelWriter('test_file2.xlsx', engine='xlsxwriter', options={'constant_memory': True})
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel.py", line 1945, in __init__
self.book = xlsxwriter.Workbook(path, **engine_kwargs)
AttributeError: module 'xlsxwriter' has no attribute 'Workbook'
My code :
import pandas pd
writer = pd.ExcelWriter('test_file.xlsx', engine='xlsxwriter', options={'constant_memory': True})
Versions
Python 3.7.3
Pandas 0.24.2
I resolved the issue. Previously, I had downloaded the xlsxwriter package and added it to my python pathmanager in Spyder. This conflicted with pandas. Deleting the path and xlsxwriter resolved the issue.

Export Python Dataframe to Excel

I'm trying to export a Python Dataframe to excel using xlsx or csv...
Here is the code I tried to use:
export_word_count = word_count.to_excel (r'C:\Users\OTR\PycharmProjects\MyProjects\word_count.xlsx', index = None, header=True)
I keep getting the following error messages:
Traceback (most recent call last):
File "C:/Users/OTR/PycharmProjects/MyProjects/CAP_Test_MotsCles.py", line 35,
in <module>
export_word_count = word_count.to_excel
(r'C:\Users\OTR\PycharmProjects\MyProjects\word_count_CAP.xlsx', index = None,
header=True)
File "C:\Users\OTR\PycharmProjects\MyProjects\venv\lib\site-
packages\pandas\core\generic.py", line 2127, in to_excel
engine=engine)
File "C:\Users\OTR\PycharmProjects\MyProjects\venv\lib\site-packages\pandas\io\formats\excel.py", line 656, in write
writer = ExcelWriter(_stringify_path(writer), engine=engine)
File "C:\Users\OTR\PycharmProjects\MyProjects\venv\lib\site-packages\pandas\io\excel.py", line 1204, in __init__
from openpyxl.workbook import Workbook
ModuleNotFoundError: No module named 'openpyxl'
Any output on this would be greatly appreciated. I tried to tweek the code, but still wouldn't export. Thank you.
EDIT:
Managed to export, but having issues with full data export
Sample Python Data:
products 58
company 53
cannabis 42
business 39
You dont have python openpyxl module installed.
Install it with:
pip install openpyxl
Your words are your index. Right now you are not exporting the index.
Try changing your code to:
word_count.to_excel (r'C:\Users\OTR\PycharmProjects\MyProjects\word_count.xlsx', index =True, header=True)
‘index=True’ is the default behavior, so not actually necessary.

datemode error using xlutils

I am trying to modify Excel files using Python, but I can't get the xlutils package to work correctly. When I try an example (from this thread):
from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')
I get the following result:
Traceback (most recent call last):
File "names3.py", line 2, in <module>
w = copy('names.xls')
File "C:\Program Files (x86)\Python27\lib\site-package
g\xlutils\copy.py", line 19, in copy
w
File "C:\Program Files (x86)\Python27\lib\site-package
g\xlutils\filter.py", line 937, in process
reader(chain[0])
File "C:\Program Files (x86)\Python27\lib\site-package
g\xlutils\filter.py", line 61, in __call__
filter.workbook(workbook,filename)
File "C:\Program Files (x86)\Python27\lib\site-package
g\xlutils\filter.py", line 287, in workbook
self.wtbook.dates_1904 = rdbook.datemode
AttributeError: 'str' object has no attribute 'datemode'
I can barely find any information about this error, I would really appreciate any help!
Thanks
xlutils.copy works on a xlrd.Book instance. You need to create such an instance first. This works:
from xlrd import open_workbook
from xlutils.copy import copy
wb = open_workbook('book1.xls')
wb_copy = copy(wb)
wb_copy.get_sheet(0).write(0,0,"foo")
wb_copy.save('book2.xls')

Categories

Resources