Python pandas UIPath - List assignment index out of range - python

I am currently facing an error
list assignment index out of range
within the invoke Python scope. I am just trying to check if each of the variables contains any of the string mentioned in 'a'. If yes then add it as a row to the excel sheet.
import pandas as pd
import xlsxwriter
def excel_data(mz01arg,p028arg,p006arg,s007arg,mz01desc,p028desc,p006desc,s007desc):
listb=[]
a=['MZ01','P028','P006','S007']
if any (x in mz01arg for x in a) is True:
listb[0] = [mz01arg]
else:
listb[0] = []
if any (x in p028arg for x in a ) is True:
listb[1] = [p028arg]
else:
listb[1] =[]
if any (x in p006arg for x in a) is True:
listb[2]=[p006arg]
else:
listb[2] = []
if any (x in s007arg for x in a) is True:
listb[3]=[s007arg]
else:
listb[3]=[]
df1 = pd.DataFrame({'SODA COUNT': listb})
df2 = pd.DataFrame({'SODA RISK DESCRIPTION': [mz01desc,p028desc,p006desc,s007desc]})
writer = pd.ExcelWriter(r"D:\Single_process_python\try_python.xlsx", engine='xlsxwriter')
df3 = pd.concat([df1,df2],axis=1)
df3.to_excel(writer,sheet_name='Sheet1', index=False)
writer.save()

You can't write to an element that does not yet exist. listb=[] creates an empty list, so there is no element with index 0. You may append items like this: listb.append(foo).
However, since you mentioned UiPath - I would recommend checking variables and their values in the workflow instead of your Python script. This way your script does one thing, and one thing exactly - and the workflow itself makes sure that all prerequisites are met. If not, you can throw and catch error messages, for example in another workflow, and ask users for input. If that logic is part of your script, this will be much harder.
Here's a very simple example:

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.

Single remove clause in while loop is removing two elements

I am writing a simple secret santa script that selects a "GiftReceiver" and a "GiftGiver" from a list. Two lists and an empty dataframe to be populated are produced:
import pandas as pd
import random
santaslist_receivers = ['Rudolf',
'Blitzen',
'Prancer',
'Dasher',
'Vixen',
'Comet'
]
santaslist_givers = santaslist_receivers
finalDataFrame = pd.DataFrame(columns = ['GiftGiver','GiftReceiver'])
I then have a while loop that selects random elements from each list to pick a gift giver and receiver, then remove from the respective list:
while len(santaslist_receivers) > 0:
print (len(santaslist_receivers)) #Used for testing.
gift_receiver = random.choice(santaslist_receivers)
santaslist_receivers.remove(gift_receiver)
print (len(santaslist_receivers)) #Used for testing.
gift_giver = random.choice(santaslist_givers)
while gift_giver == gift_receiver: #While loop ensures that gift_giver != gift_receiver
gift_giver = random.choice(santaslist_givers)
santaslist_givers.remove(gift_giver)
dummyDF = pd.DataFrame({'GiftGiver':gift_giver,'GiftReceiver':gift_receiver}, index = [0])
finalDataFrame = finalDataFrame.append(dummyDF)
The final dataframe only contains three elements instead of six:
print(finalDataframe)
returns
GiftGiver GiftReceiver
0 Dasher Prancer
0 Comet Vixen
0 Rudolf Blitzen
I have inserted two print lines within the while loop to investigate. These print the length of the list santaslist_receivers before and after the removal of an element. The expected return is to see original list length on the first print, then minus 1 on the second print, then the same length again on the first print of the next iteration of the while loop, then so on. Specifically I expect:
6,5,5,4,4,3,3... and so on.
What is returned is
6,5,4,3,2,1
Which is consistent with the DataFrame having only 3 rows, but I do not see the cause of this.
What is the error in my code or my approach?
You can solve it by simply changing this line
santaslist_givers = santaslist_receivers
to
santaslist_givers = list(santaslist_receivers)
Python variables are pointers essentially so they refer to the same list , ie santaslist_givers and santaslist_receivers were accessing the same location in memory in your implementation . To make them different use a list function
And for some extra information , you can refer copy.deepcopy
You should make an explicit copy of your list here
santaslist_givers = santaslist_receivers
there are multiple options for doing this as explained in this question.
In this case I would recommend (if you have Python >= 3.3):
santaslist_givers = santaslist_receivers.copy()
If you are on an older version of Python, the typical way to do it is:
santaslist_givers = santaslist_receivers[:]

Add to dictionary in if loop

I have an if loop in which I am trying to;
(1) Create a dataframe from a filepath.
(2) Format this dataframe
(3) Add that dataframe to a dictionary that is a property of an instance of a class.
Here is my code defining the class and the method:
class myClass:
def __init__(self, name, filepathlist):
self.name = name
self.filepathlist = filepathlist
def formatData(self):
i = 0
self.dataframeDict = {}
if i < (len(self.filepathlist) - 1):
DFRAW = pd.read_csv(self.filepathlist[i], header = 9) #Row 9 is the row that is not blank (all blank auto-skipped)
DFRAW['DateTime'], DFRAW['dummycol1'] = DFRAW[' ;W;W;W;W'].str.split(';', 1).str
DFRAW['Col1'], DFRAW['dummycol2'] = DFRAW['dummycol1'].str.split(';', 1).str
DFRAW['Col2'], DFRAW['dummycol3'] = DFRAW['dummycol2'].str.split(';', 1).str
DFRAW['Col3'], DFRAW['Col4'] = DFRAW['dummycol3'].str.split(';', 1).str
DFRAW = DFRAW.drop([' ;W;W;W;W', 'dummycol1', 'dummycol2', 'dummycol3'], axis = 1)
dictIndex = self.filepathlist[i][39:44]
self.dataframeDict.update({dictIndex: DFRAW})
i = i + 1
Then I create an instance of the class and run the method:
filepathlist = ['filepath1','filepath2']
myINST = myClass('Mydataname', filepathlist)
myINST.formatData()
I then expect myINST.dataframeDict to have two dataframes as per the 2 input filepaths and thus 2 iterations of the if loop. However only 1 is present.
What is the error in my code or my approach?
It is hard to tell whether this will completely solve your problem, because no dummy data is provided. You will, however, get one step closer to your solution if you replace if i < (len(self.filepathlist) - 1): with while i < (len(self.filepathlist) - 1):.
You are currently just checking if i=0 is smaller than len(self.filepathlist)-1. If so, then the if-block is executed once. What you are actually looking for is a loop that keeps on iterating, as long as i is smaller than len(self.filepathlist)-1. This is done with while-loops.
You need to change your condition to for i in range(len(self.filepathlist)):
(Also, remove the assignment of i as the for loop does it automatically. For the same reason, you should also remove the line which increments i).
If you want to use a while loop, change the if line to while i < len(self.filepathlist):.
Notice that there's no -1. This is because you're using < instead of <=. If you want to use -1, then you also need the <= as this will ensure the loop runs the correct number of times.

Concatenate several variables does not work inside iterations and works outside of iterations

I am trying to concatenate several variables and calculate the sum and since I want to do multiple operations, I am iterating through all the possible combinations of variables which are already saved in the df.cols but I get key error.
for i in df.cols[0:20]:
k+=1
name = "cat" + str(k)
df1[name] = df1.loc[:, i].sum(axis = 1)
It gives KeyError although it is in the columns.
KeyError: "the label [['D120_1', 'Y69_0', 'K189_0']] is not in the [columns]"
For example, when I try to print i:
print(i)
['D120_1', 'Y69_0', 'K189_0']
and when I try it without iteration replacing the i with ['D120_1', 'Y69_0', 'K189_0'] it works well. Why does it recognize the key inside iteration and does not recognize it outside the iteration.
This works well although the same thing as in the iteration.
df1["col1"] = df1.loc[:, ['D120_1', 'Y69_0', 'K189_0']].sum(axis = 1)
But this does not work:
df1["col1"] = df1.loc[:, i].sum(axis = 1)
If remember correctly in Pandas both start and stop index are included in the slice as opposed to how Python does it where the last index is skipped. See if that is the source of your problem - you may be iterating to an unavailable index(label).
Actually, I discovered that the list was saved as string "['D120_1', 'Y69_0', 'K189_0']"
To solve the problem I used ast.literal_eval
from ast import literal_eval
i = literal_eval(i)
print(i)
['D120_1', 'Y69_0', 'K189_0']

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