I am trying to retrieve the defined names scoped to a particular worksheet in an Excel file using worksheet.defined_names, however this always returns an empty dict.
I have, of course, confirmed that my Excel file does indeed have a defined name scoped to the worksheet in question, and that I am accessing the correct worksheet.
When switching the scope of the defined name in question to the workbook (i.e. global scope) and using workbook.defined_names everything works and I am getting the dict I expected.
EDIT
To clarify, when setting the defined names' scope to worksheet, they don't show up at all, even when using workbook.defined_names.
EDIT - END
I have checked the documentation but this didn't help as I am using worksheet.defined_names as described there.
Does anyone know why I am having this issue?
Related
I am using python 3.9.6 in Windows 10.
Similar earlier questions at
(1) Creating a dynamic dictionary name
and
(2) How to obtain assembly name dynamically
were different and do not solve my problem.
My data dictionary(dynamically created):
pcm30={'ABB': '-0.92', 'ZYDUSWELL': 2.05}
Dynamically obtained new dictionary name "pCh0109" is in variable z
I have to create different dictionaries to create a data frame.
Now I want to dynamically (i.e through programming) change the name of the dictionary from
'pcm30'
to
'pCh0109'.
The digits in the new name of the dictionary ('pCh0109') indicate the time of creation of the particular dictionary.
How to do it?
Will be grateful for assistance and help.
I would strongly recommend you don't try this unless you absolutely have to, but here's the simplest approach to do that:
pcm30 = {'ABB': '-0.92', 'ZYDUSWELL': 2.05}
globals()['pCh0109'] = globals().pop('pcm30')
# Your IDE might glare at you here, but it'll work out without errors at runtime
print(pCh0109)
Instead I suggest to try this approach - use a dictionary if possible. This will turn out much safer for all. Example below:
def my_func():
d = {}
pcm30 = {'ABB': '-0.92', 'ZYDUSWELL': 2.05}
d['pCh0109'] = locals().pop('pcm30')
print(d['pCh0109']['ABB'])
# -0.92
So, I have function ABC in a certain .py file that returns a list. And in ANOTHER .py FILE, i have another function where I'm supposed to write into an empty file (that function will return that new file). I want to write into that new empty file my list gotten with the function ABC. How am I supposed to do that?
Obs - sorry for not posting any code but I really have no ideas about how to do this, besides that I've found nothing in another questions similars to this.
https://www.learnpython.org/en/Functions has a very good section on how to use functions and the following sections on classes, objects and modules are worth reviewing.
Write a file:
Python 2.7 : Write to file instantly
Passing args vs list:
Advantages of using *args in python instead of passing a list as a parameter
That gives you a starting point for learning Python and solving your immediate problem.
I am trying to sort a spreadsheet using openpyxl and Python. I have read the documents and I don't quite understand this page. I am expecting it to either add the auto filter dropdown arrows or sort my spreadsheet and it is returning errors. Here's my code
wb = openpyxl.load_workbook('report.xlsx')
ws = wb.active
ws['A2'] = "Store"
ws['B2'] = "Manager"
ws['C2'] = "Zone"
ws.column_dimensions.group('F','DU',hidden=True)
#ws.AutoFilter.add_sort_condition('C:C')
wb.save("report.xlsx")
According to the documents it looks like the line "ws.AutoFilter.add_sort_condition('C:C')" should give me the result I want. (Yes I understand it is currently a comment line. The rest of my code runs fine without that line so I commented it.)
When I have that line in the code I get the error - 'Worksheet' object has no attribute 'AutoFilter' but according to the documents it looks like it does. http://openpyxl.readthedocs.org/en/latest/_modules/openpyxl/worksheet/filters.html#AutoFilter.
If anyone can help explain to me why it is failing or what the documents mean that would be great.
This statement in the documents is particularly confusing to me:
"Don't create auto filters by yourself. It is created by :class:~openpyxl.worksheet.Worksheet.
You can use via :attr:~~openpyxl.worksheet.Worksheet.auto_filter attribute."
because I tried that too and it also failed.
Update: #crussell's reply worked in that it added the auto filter to my spreadsheet. However, it is still not adding the sort condition to the appropriate column.
See here: http://openpyxl.readthedocs.org/en/latest/api/openpyxl.worksheet.html?highlight=auto_filter#openpyxl.worksheet.worksheet.Worksheet.auto_filter
The auto_filter command returns the AutoFilter object, so in a sense they are the same thing.
What you need is ws.auto_filter.ref = 'C1:C20'
with the range of cells those of which you want to filter.
According to the documentation openpyxl can define the filter and/or sort but does not apply them!
They can only be applied from within Excel
I don't have a full answer for this, but I did find something interesting when using filters.
I added a filter column,
eg:
ws.auto_filter.add_filter_column(1,{},True)
then I opened the resulting spreadsheet. The column showed the filter! But the data was not actually filtered in the spreadsheet. I had to click on the "Data" tab and click "Reapply" the filter.
So it looks like the adding of a sort or filter column works, except it never actually applies the sort or filter.
I have been hunting down a function that will apply the filter, but have not yet had any luck. If anyone has thoughts, I'd love to hear them!
Thanks!
After looking at the documentation and the source code for the AutoFilter.add_sort_condition() function it looks like the ref you're providing may need to be changed to include row indices, like "C1:C120", for example. Have you tried it with specific row numbers? Also, be sure to take a look at the comment regarding the ref variable right below the function declaration in:
http://openpyxl.readthedocs.org/en/latest/_modules/openpyxl/worksheet/filters.html#AutoFilter
if you're not following where I'm coming from. Cheers and good luck!
Is there a way to find the index of a variable in SPSS Python?
For example, if one of my variables in the SPSS dataset is ID
usually, I would be able to access the variable with the following code:
varObj = datasetObj.varlist[0]
Assuming that ID is the first column in my dataset.
But what if the variable ID is lost somewhere in the middle of a dataset?
Is there a way for me to find the index value of the variable ID?
Thank you very much for your help.
From the documentation of the Variable Class, you can get a reference to the variable by name or by index:
# Create a Variable object, specifying the variable by name
varObj = datasetObj.varlist['bdate']
# Create a Variable object, specifying the variable by index
varObj = datasetObj.varlist[3]
So in your case:
varObj = datasetObj.varlist['ID']
You can, if needed, get the index of the variable by its name, using the index property:
varIndex = datasetObj.varlist['ID'].index
Note also that you can use the spssaux.VariableDict class to get and set (except for type) all the properties of variables.
Also, all the doc for the programmability apis is available under Help > Programmability, and you may find the Programming and Data Management book (pdf) downloadable from the SPSS Community (old) or new Predictive Analytics website at https://developer.ibm.com/predictiveanalytics/
The documentation for xlrd here
http://www.python-excel.org/
mentions that it is now possible in latest version, but does not say how.
I'm not sure what you are actually reading; xlrd access to named ranges has been available for some years now (in version 0.6.0; latest version is 0.7.1) and came with full documentation ab initio.
This is the xlrd documentation link that's given on the http://www.python-excel.org/ page that you mentioned. Hit PageDown twice and you should see a section headed Named references, constants, formulas, and macros. This gives an overview and points you to documentation of the Book.name_* methods & the Name object, and to a demonstration script.
Note that this is the SVN trunk version of the documentation and applies to a future release; it may mention one extra convenience method that's not available in the current released version of xlrd (which you can get from PyPI) and which includes the relevant documentation file.
Update in response to """I got this far: someRange = book.name_map[u'somerange'][0] and now I want to iterate over it, grab values, get its dimensions, etc. Now what do I do? I tried dir(someRange) and help(someRange) and it has not helped much."""
What you are calling someRange is an instance of the Name class. You need to read the documentation of that class. It would help if you were to read the demonstration script xlrdnameAPIdemo.py and try running it over your xls file(s). Note that "get its dimensions" logically precedes "iterate over it, grab values"; the convenience method Name.area2d may be what you need.
It's not trivial and it worked in my case only on XLS no XLSX (probably because on my XLSX name.evaluated == 0):
name = book.name_map['my_named_range'][0]
assert name.result.kind == xlrd.oREF
ref3d = name.result.value[0]
for sheet_index in range(ref3d.shtxlo, ref3d.shtxhi):
sheet = book.sheet_by_index(sheet_index)
for row in range(ref3d.rowxlo, min(ref3d.rowxhi, sheet.nrows)):
for col in range(ref3d.colxlo, min(ref3d.colxhi, sheet.ncols)):
cell = sheet.cell(row, col)
# TODO: Do something with that cell.
You want to limit the number of columns and rows in the sheet in case your range is like A:A or 1:1 (i.e., the entire row or column).