Parsing a column using openpyxl - python

I have the following algorithm to parse a column for integer values:
def getddr(ws):
address = []
col_name = 'C'
start_row = 4
end_row = ws.get_highest_row()+1
range_expr = "{col}{start_row}:{col}{end_row}".format(col=col_name, start_row=start_row, end_row=end_row)
for row in ws.iter_rows(range_string=range_expr):
print row
raw_input("enter to continue")
cell = row[0]
if str(cell.value).isdigit:
address.append(cell.value)
else:
continue
return address
This crashes at cell = row[0] saying "IndexError: tuple index out of range", and i dont know what this means. I tried printing out row to see what it contained, but all it gives me is an empty set of parentheses. Anyone know what I'm missing?

That is not so easy to say what is the problem you have, because there are no input data that you are trying to process.
But I can explain what is the reason of the error you've get, and in which direction you must go. The list row contains 0 elements (row = []), because of that you can not say row[0] — there are no row[0]. The first thing you must change is check, how long is your list, and when if it is long enough make other things:
for row in ws.iter_rows(range_string=range_expr):
print row
raw_input("enter to continue")
if len(row) > 0:
cell = row[0]
if str(cell.value).isdigit:
address.append(cell.value)
else:
continue
That is the first step that you must do anyway.

Related

Dataframe Is No Longer Accessible

I am trying to make my code look better and create functions that do all the work from running just one line but it is not working as intended. I am currently pulling data from a pdf that is in a table into a pandas dataframe. From there I have 4 functions, all calling each other and finally returning the updated dataframe. I can see that it is full updated when I print it in the last method. However I am unable to access and use that updated dataframe, even after I return it.
My code is as follows
def data_cleaner(dataFrame):
#removing random rows
removed = dataFrame.drop(columns=['Unnamed: 1','Unnamed: 2','Unnamed: 4','Unnamed: 5','Unnamed: 7','Unnamed: 9','Unnamed: 11','Unnamed: 13','Unnamed: 15','Unnamed: 17','Unnamed: 19'])
#call next method
col_combiner(removed)
def col_combiner(dataFrame):
#Grabbing first and second row of table to combine
first_row = dataFrame.iloc[0]
second_row = dataFrame.iloc[1]
#List to combine columns
newColNames = []
#Run through each row and combine them into one name
for i,j in zip(first_row,second_row):
#Check to see if they are not strings, if they are not convert it
if not isinstance(i,str):
i = str(i)
if not isinstance(j,str):
j = str(j)
newString = ''
#Check for double NAN case and change it to Expenses
if i == 'nan' and j == 'nan':
i = 'Expenses'
newString = newString + i
#Check for leading NAN and remove it
elif i == 'nan':
newString = newString + j
else:
newString = newString + i + ' ' + j
newColNames.append(newString)
#Now update the dataframes column names
dataFrame.columns = newColNames
#Remove the name rows since they are now the column names
dataFrame = dataFrame.iloc[2:,:]
#Going to clean the values in the DF
clean_numbers(dataFrame)
def clean_numbers(dataFrame):
#Fill NAN values with 0
noNan = dataFrame.fillna(0)
#Pull each column, clean the values, then put it back
for i in range(noNan.shape[1]):
colList = noNan.iloc[:,i].tolist()
#calling to clean the column so that it is all ints
col_checker(colList)
noNan.iloc[:,i] = colList
return noNan
def col_checker(col):
#Going through, checking and cleaning
for i in range(len(col)):
#print(type(colList[i]))
if isinstance(col[i],str):
col[i] = col[i].replace(',','')
if col[i].isdigit():
#print('not here')
col[i] = int(col[i])
#If it is not a number then make it 0
else:
col[i] = 0
Then when I run this:
doesThisWork = data_cleaner(cleaner)
type(doesThisWork)
I get NoneType. I might be doing this the long way as I am new to this, so any advice is much appreciated!
The reason you are getting NoneType is because your function does not have a return statement, meaning that when finishing executing it will automatically returns None. And it is the return value of a function that is assigned to a variable var in a statement like this:
var = fun(x)
Now, a different thing entirely is whether or not your dataframe cleaner will be changed by the function data_cleaner, which can happen because dataframes are mutable objects in Python.
In other words, your function can read your dataframe and change it, so after the function call cleaner is different than before. At the same time, your function can return a value (which it doesn't) and this value will be assigned to doesThisWork.
Usually, you should prefer that your function does only one thing, so expect that the function changes its argument and return a value is usually bad practice.

Include a header from Excel in a for loop with openpyxl

I am trying to include a header when printing data in a column.
Issue
But when I try it an error comes up:
TypeError: '<' not supported between instances of 'int' and 'str'
Code
def pm1():
for cell in all_columns[1]:
power = (cell.value)
if x < power < y:
print(f"{power}")
else:
print("Not steady")
pm1()
I know you cannot compare an string with operation values.
How can I include the header while looping throughout the entire column?
Based on what I understand from your comments, this may work for you.
def pm1():
for cell in all_columns[1]:
for thing in cell:
# in openpyxl you can call on .row or .column to get the location of your cell
# you said you wanted to print the header (row 1), a sting
if thing.row == 1:
print(thing.value)
else:
# you said that the values under the header will be a digit
# so now you should be safe to set your variable and make a comparison
power = thing.value
if x < power < y:
print(f"{power}")
else:
print("Not steady")
So you are looping through all cells of a column, here given by a first column all_columns[1].
Assume the first cell of each column might contain a header which has a value is of type string (type(cell.value) == str).
Then you have to possibilities:
Given the first cell of each column (in row 1) is a header, take advantage of that position
If all other cells contain numerical values, you can handle only the str values differently as supposed headers
def power_of(value):
# either define boundaries x,y here or global
power = float(value) # defensive conversion, some values might erroneously be stored as text in Excel
if x < power < y:
return f"{power}"
return "Not steady" # default return instead else
def pm1():
for cell in all_columns[1]:
if (cell.row == 1): # assume the header is always in first row
print(cell.value) # print header
else:
print(power_of(cell.value))
pm1()

Detecting a change in a CSV row

I am trying to find a way to detect when string elements in csv file change values. When the value changes, I want the operation of the program to change. I want to read the value in the for loop one step ahead and compare it to the current value. Unfortunately my research has only turn up results that step the for loop ahead by one rather than simply reading the value.
Any help would be appropriated.
import csv
with open("bleh.csv", "r") as bleh:
blehFileReader = csv.reader(bleh, delimiter=',')
next(blehFileReader, None)
for row in blehFileReader:
name = row
nextname = next(blehFileReader)
print(name)
if name != nextname:
print ("name has changed")
Instead of looking at the next name, look at the previous one:
previous_name = None
for row in blehFileReader:
if row != previous_name:
print ("name has changed")
....
previous_name = row

Check OrderedDict based on index in csv?

I'm trying to do different checks based on the index number of a dictionary. So, if index == 0, do something, otherwise if index>0, do something else.
I was trying to use OrderedDict and index it based on items(). But if I say, od.items()[0], it just gives me the name of the first element. Not the ability to write an if conditional based on whether the first element has already been checked.
Also I would prefer not to check my conditional based on the actual value in the example.csv file, since it will change daily.
Here is my code and example data in the csv file.
Example.csv
Key_abc, Value894
Key_xyz, Value256
Key_hju, Value_567
Code:
with open('example.csv','rb') as f:
r = csv.reader(f)
od = collections.OrderedDict(r)
for row in od:
if od.items() == 0:
print 'do some checks and run code'
print row, od[row]
elif od.items() > 0:
print 'go through code without checks'
print row, od[row]
Maybe you could do something like this. (The example below is written in python3 syntax).
#ExampleCode
with open('example.csv') as f:
r = csv.reader(f)
od = collections.OrderedDict(r)
for index, row in zip(collections.count(), od):
if index == 0:
print('do some checks and run code')
print(row, od[row])
elif index > 0:
print('go through code without checks')
print(row, od[row])

detect EOF of excel file in Python

I have written a code for detecting the EOF of an excel file using python:
row_no = 1
while True:
x = xlws.Cells(row_no,1).value
if type(x) is None:
break
else:
print(len(x))
print(x)
row_no = row_no + 1
i expect the while loop will stop then x becomes a "blank cell", which I support to be None, but it doesn't work, and it go to len(x) and prompt me an error of NoneType has no len. Why?
Thanks!
This here is your problem:
if type(x) is None:
If x is None, its type is NoneType. Therefore, this is never true, so you never see the blank cell and you end up trying to get the length of None.
Instead, write:
if x is None:
It looks like you are using pywin32com ... you don't need to loop around finding "EOF" (you mean end of Sheet, not end of File).
If xlws refers to a Worksheet object, you can use this:
used = xlws.UsedRange
nrows = used.Row + used.Rows.Count - 1
to get the effective number of rows in the worksheet. used.Row is the 1-based row number of the first used row, and the meaning of used.Rows.Count should be rather obvious.
Alternative: use xlrd ... [dis]claimer: I'm the author.
As mentioned in other comments you can use 'xlrd' as well to know the limits of the excel file as:
workbook = xlrd.open_workbook (excel_loc)
excel_sheet = workbook.sheet_by_index(0)
print("no of rows: %d" %excel_sheet.nrows)
print("no of cols: %d" %excel_sheet.ncols)

Categories