First of all I would just like to mention - I am a beginner, I am still learning. This code is probably an abomination and I might be missing something obvious, please be nice.
My question is this. I have written a for loop to find the highest earning employee but I would like for the user to select a start and end date for their earnings to be calculated.
So for example my program should be able to calculate an employees earning from 01/05/2021 to 09/05/2021.
The only thing I'm struggling with is how to reference the date, I've been googling for an hour but the responses are just too complicated for me.
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime as dt
df = pd.read_csv('Task_4a_data.csv', index_col='ID')
#main menu
def menu():
print("\t\t****MAIN MENU****")
print('1) Enter sales records')
print('2) Run reports')
x = int(input(""))
return x
#reports menu
def menu2():
print("**** Reports Dashboard ****")
print("1. Individual Employee Report")
print("2. Show employees with the highest sales value")###########
x = int(input(""))
return x
def ind_emp_check(df_r, id, date1, date2):
df_r = df_r.loc[df.index == id]
df_r = df_r.T[3:]
df_r.reset_index(inplace=True)
df_r['ID1'] = pd.to_datetime(df_r['index'], format='%d/%m/%Y')
date1 = pd.to_datetime(date1, format='%d/%m/%Y')
date2 = pd.to_datetime(date2, format='%d/%m/%Y')
mask = (df_r['ID1'] >= date1) & (df_r['ID1'] <= date2)
df_search = df_r.loc[mask]
print(df_search)
print('Total by id = {} is {}'.format(id, sum(df_search[id])))
plt.bar(df_search['index'], df_search[id])
plt.xticks(rotation=90)
plt.show()
y = menu()
while y == 1 or y == 2:
if y == 1:
try:
ID = int(input("Enter the Staff ID "))
if ID not in df.index.values:
print('yes')
date1 = input("Enter Date in dd/mm/yy: ")
day, month, year = date1.split("/")
date1 = datetime.date(int(year), int(month), int(day))
if datetime.datetime.strptime(date1.strftime('%d/%m/%Y'), '%d/%m/%Y') > datetime.datetime.strptime(
dt.today().strftime('%d/%m/%Y'), '%d/%m/%Y'):
print("Date is in the future")
else:
cost = float(input("Enter the cost : "))
df.loc[ID, date1.strftime('%d/%m/%Y')] = cost
# df.to_csv('test2.csv')
except:
print("\n\nError Occurred Please try again\n\n")
y = menu()
if y == 2:
x = menu2()
if x == 1:
try:
id = int(input("Enter the Employee Id : "))
s_date = input("Enter Starting Date in dd/mm/yyyy: ")
day, month, year = s_date.split("/")
s_date = datetime.date(int(year), int(month), int(day))
e_date = input("Enter End Date in dd/mm/yyyy: ")
day, month, year = e_date.split("/")
e_date = datetime.date(int(year), int(month), int(day))
s_date = datetime.datetime.strptime(s_date.strftime('%d/%m/%Y'), '%d/%m/%Y')
e_date = datetime.datetime.strptime(e_date.strftime('%d/%m/%Y'), '%d/%m/%Y')
ind_emp_check(df, id, s_date, e_date)
except:
print("\n\nError Occurred Please try again\n\n")
x = menu2()
elif x == 2:
s_date = input("Enter Starting Date in dd/mm/yyyy: ")
e_date = input("Enter End Date in dd/mm/yyyy: ")
total = 0
totals = []
for r in df.index:
for i in (df.loc[r]):
if PLACEHOLDER == e_date:
break
try:
total+=i
total = int(total)
except:
pass
totals.append(total)
total=0
largest_number = totals[0]
for number in totals:
if number > largest_number:
largest_number = number
print(largest_number)
else:
x = menu2()
else:
x = menu()
x = menu()```
Related
I am getting the Attribute error:
'float' object has no attribute 'replace'
In my program i am reading 3 different files. When i run the code it works perfectly, but only for one of the files. I have no clue why the other 2 files give me this error. I was excpecting to get the amount of days in a given month from a .csv file. i am writing the code in python. If you need any aditional information please ask :)
Code below:
import pandas as pd
def getAMSdata(fileName):
startTid = []
sluttTid = []
forbruk = []
dataframe= pd.read_csv(fileName, sep=";")
startTid = dataframe["Fra"].tolist()
sluttTid = dataframe["Til"].tolist()
forbruk = dataframe["KWH 60 Forbruk"].tolist()
return startTid,sluttTid,forbruk #returnerer lister
dataLists = getAMSdata("data/meteringvalues-mp-xxxxx-consumption-202101.csv")
for i in range(len(dataLists[2])):
dataLists[2][i] = float(dataLists[2][i].replace(',','.'))
def getDayCount(timeStampList):
dayCount= len(timeStampList) // 24
return dayCount
def getMonth(dateAndTimeStr):
months = ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"]
monthStr = int(dateAndTimeStr[3:5])
month = months[monthStr - 1]
return month
def getDays(timeStampList):
#-------------------------------------
dayList = []
for i in range(0, len(timeStampList)):
dayList.append(int(timeStampList[i][0:2]))
#-------------------------------------
return dayList
def getHours(timeStampList):
#-------------------------------------
hourList = []
for i in range(len(timeStampList)):
hourList.append(int(timeStampList[i][11:13]))
#-------------------------------------
return hourList
import os
files = os.listdir('data')
def selectDataFile(fileIndex):
return files[fileIndex]
selectDataFile(0)
def printMainMenu():
print('\n')
print('------ MAIN MENU ------')
print('\n')
print('1) Show all the data files available.')
print('2) Select the year and month to study.')
print('3) Go to graph and statistics menu.')
print('4) Quit.')
return
def printMonth():
print('1 : January')
print('2 : February')
print('3 : March')
print('4 : April')
print('5 : May')
print('6 : June')
print('7 : July')
print('8 : August')
print('9 : September')
print('10 : October')
print('11 : November')
print('12 : December')
def processMainMenu(x, currentfile):
print('\n')
if x=='1' :
print("Files availables : ")
for i in range(len(files)):
print(files[i])
return True, currentfile
elif x=='2':
year = input('\nSelect the year : ')
if year != '2020' and year != '2021':
print('There is no data for ', year)
return True, currentfile
printMonth()
month = input('\nSelect the month : ')
if year == '2021' and month == '1':
currentfile = selectDataFile(1)
return True, currentfile
elif year =='2020' and month == '11':
currentfile= selectDataFile(0)
return True, currentfile
elif year =='2020' and month == '12':
currentfile = selectDataFile(2)
return True, currentfile
else :
print('There is no data for the selected year and month.')
return True, currentfile
elif x=='3':
if currentfile == '':
print('Select a file before going to the graph and stats menu.')
return True, currentfile
printGraphStatMenu()
y = input('Chose an option by entering its index number : ')
keepGoing = processGraphStatMenu(y, currentfile)
return keepGoing, currentfile
elif x=='4':
return False, currentfile
else:
print('Please enter a proper index number.')
return True,currentfile
def printGraphStatMenu():
print('\n')
print(' ------ GRAPH AND STATISTICS MENU ------')
print('\n')
print(' STATISTICS : ')
print(' 1) Show the number of days in the month.')
print(' 2) Show the average consumption in the month.')
print(' 3) Show the average hourly consumption per day.')
print(' 4) Chose an hour of the day and show its consumption.')
print(' 5) Show highest consumption and the hour it is reached.')
print(' 6) Show the average power peak in the month.')
print(' 7) Show standard deviation for the hourly consumption.')
print(' GRAPHS : ')
print(' 8) Graph the daily consumption.')
print(' 9) Graph an average day.')
print(' 10) Quit.')
def processGraphStatMenu(y, currentfile):
data = getAMSdata(str('data/' + currentfile))
for i in range(len(data[2])):
data[2][i] = float(data[2][i].replace(',','.'))
if y == '1':
print('\n THERE ARE ', getDayCount(data[0]),' DAYS IN THE MONTH.')
return True
elif y== '2':
print('\n THE AVERAGE CONSUMPTION IN THE MONTH IS :', getAverage(data[2]), 'KWH.')
return True
elif y=='3':
avgDay = pd.DataFrame(getAvgDay(data[2], getHours(data[0])))
print('\n THE AVERAGE HOURLY CONSUMPTION PER DAY IS :', avgDay , 'KWH.')
return True
elif y=='4':
hour = int(input(' Select an hour by entering an integer between 0 and 23 :'))
if hour < 0 or hour > 23 :
print('\n Please enter an hour between 0 and 23.')
return True
hours = getHours(data[0])
sameHourCons = []
for i in range(len(hours)):
if hours[i] == hour :
sameHourCons.append(data[2][i])
index = range(1, len(sameHourCons) + 1)
sameHourConsDF = pd.DataFrame(sameHourCons, index = index)
print('\n HERE IS THE CONSUMPTION AT HOUR ', hour, ' FOR EACH DAY OF THE MONTH : \n', sameHourConsDF)
return True
elif y == '5':
peakCons, peakDate, peakHour = findPeakInterval(data[2], getDays(data[0]), getHours(data[0]))
print('\n THE HIGHEST CONSUMPTION IS : ', peakCons, ' KWH. IT IS REACHED ON DAY ', peakDate, ' AT HOUR ', peakHour,'.')
return True
elif y == '6':
print('\n THE AVERAGE POWER PEAK IN THE MONTH IS : ', getEffectPeak(data[2]), 'KWH')
return True
elif y == '7':
hourlyCons = getDailyConsumption(data[2], getDays(data[0]))
print('\n THE STANDARD DEVIATION FOR THE HOURLY CONSUMPTION IS :', getStdDev(hourlyCons, getAverage(hourlyCons)), 'KWH.')
return True
elif y == '8':
plotDailyConsumption(getDailyConsumption(data[2], getDays(data[0])), getMonth(data[0][0]))
return True
elif y == '9':
plotAvgDay(getAvgDay(data[2], getHours(data[0])), getMonth(data[0][0]))
return True
elif y == '10' :
return False
else:
print('\n Please enter a proper index number.')
return
def main():
keepGoing = True
currentfile = ''
while(keepGoing):
printMainMenu()
x = input('Chose an option by entering its index number : ')
keepGoing, currentfile = processMainMenu(x, currentfile)
print('Bye !')
return
main()
I skipped some parts that I assumed were unimportant for my error
fyi this is my first major code and my first stack overflow question
I assume you're coding in Python.
In Python, you cannot write .replace('x', 'y') for floats, but you can for strings. Different types have different properties.
A very basic way of replacing floats with another number is as follows:
a = 5.5
if a == 5.5:
a = 9.3
There are many ways to change a float, but which one to use depends on your specific problem.
import pandas as pd
id_num=[101,102,103,104]
price = [40,50,60,70]
stock = [10,14,14,13]
new = pd.DataFrame(
{'id_num':id_num,
'price':price,
'stock':stock
})
try:
inp_num=int(input("enter the id number:"))
qua = int(input("enter the quantity:"))
except ValueError:
print("Invalid")
if([new['id_num']==inp_num]):
total = price*qua
print(total)
Explanation
Program : enter the id and stock value that customer wants to buy and calculate the price according the quantity Example input : 1 >
id = 101
quantity = 5 output :
total price = 200 2> id = 103 quantity = 20 output ; out of stock"
Here is the final solution
id_num=[101,102,103,104]
price = [40,50,60,70]
stock = [10,14,14,13]
try:
inp_num=int(input("enter the id number:"))
qua = int(input("enter the quantity:"))
except ValueError:
print("Invalid")
if inp_num in id_num:
ind = id_num.index(inp_num)
if qua <= stock[ind]:
total = price[ind]*qua
stock[ind] -= qua
print(total)
else:
print("out of stock")
else:
print("no product available")
import pandas as pd
def new_funct(new):
try:
inp_num=int(input("enter the id number:"))
qua = int(input("enter the quantity:"))
except ValueError:
print("Invalid")
list_of_value = new['id_num'].tolist()
if inp_num in list_of_value:
index_prod = list_of_value.index(inp_num)
if qua <= new['stock'][index_prod]:
total = new['price'][index_prod]*qua
new.at['stock', index_prod] = new['stock'][index_prod] - qua
print("total price =",total)
else:
print("out of stock")
else:
print("no product available")
return new
id_num=[101,102,103,104]
price = [40,50,60,70]
stock = [10,14,14,13]
new = pd.DataFrame({'id_num':id_num,'price':price,'stock':stock})
while True:
new_funct(new)
def dateCalculationNorm(year):
a = year%19
b = year%4
c = year%7
d = (19*a + 24)%30
e = (2*b + 4*c + 6*d + 5)%7
dateNumber = 22 + d + e
return dateNumber
def dateCalculationSpecial(year):
a = year%19
b = year%4
c = year%7
d = (19*a + 24)%30
e = (2*b + 4*c + 6*d + 5)%7
dateNumber = 15 + d + e
return dateNumber
def dateOutput(year, date):
print("The date of Easter in the year {0} is {1}.".format(year, date))
def main():
print("Easter Date Calculator")
print()
year = eval(input("Enter the year: "))
if year >= 1900 and year <= 2099:
dateCalculationNorm(year)
if dateNumber > 31:
date = "April " + str(dateNumber - 31)
dateOutput(year, date)
else:
date = "March " + str(dateNumber)
dateOutput(year, date)
elif year == 1954 or year == 1981 or year == 2049 or year == 2076:
dateCalculationSpecial(year)
if dateNumber > 31:
date = "April " + str(dateNumber - 31)
dateOutput(year, date)
else:
date = "March " + str(dateNumber)
dateOutput(year, date)
else:
print("Sorry, but that year is not in the range of this program.")
if __name__ == '__main__':
main()
I am having trouble getting main() to accept dateNumber in the line following
(if year >= 1900 and year <=2099) Python is saying that dateNumber is not defined. I tried making dateNumber global at the beginning of the program and that worked (albeit with a warning from Python), but I know that's the sloppy way to get this program working.
Any help is very much appreciated.
You need to instantiate dateNumber.
if year >= 1900 and year <= 2099:
dateNumber = dateCalculationNorm(year) # Instantiate here.
if dateNumber > 31:
date = "April " + str(dateNumber - 31)
dateOutput(year, date)
else:
date = "March " + str(dateNumber)
dateOutput(year, date)
As it stands, there's nothing like that inside your main() function. There's no need to set it to a global either.
import datetime
def main():
date_string = input('Enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
while month < 1 or month > 12:
print('Month entered is out of range')
date_string = input('Re-enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
while day < 1 or day > 31:
print('Day entered is out of range')
date_string = input('Re-enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
while year != 13:
print('Year does not represent 2013')
date_string = input('Re-enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
print(month, day, year)
main()
When I run the program and enter months and days that are invalid, it progresses down until the year validation and will keep posting that prompt even if the input is invalid for one of the other inputs.
You could arrange this differently:
while True:
date_string = input('Enter a date in mm/dd/yy format: ')
date_list = date_string.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
if month < 1 or month > 12:
print('Month entered is out of range')
elif day < 1 or day > 31:
print('Day entered is out of range')
elif year != 13:
print('Year does not represent 2013')
else:
break
print(month, day, year)
Start again.
You don't want three little while loops. You want one big while loops ( while not success ) with three if statement to make the three checks and if any one fails, set success to false.
I am trying to test user input, but it only seems to work the first time through. If I give the correct data the first time, it works, but if I originally give the wrong data and then use the correct data after being re-prompted it never recognizes it as correct. Any idea why it works the first time but not any time after that? Here is the code,
testDate = open("Sales.txt")
def DateTest(Date, Position):
firstTry = True
validSyntax = False
Done = False
while Done == False:
while validSyntax == False:
if firstTry == True:
print "debug 2"
try:
Date = Date.strip().split(',')
Year = int(Date[0])
Month = int(Date[1])
Day = int(Date[2])
Date = (Year, Month, Day)
except:
print "That is invalid input."
firstTry = False
else:
validSyntax = True
print "ok got it"
elif firstTry == False:
NewDate = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
NewDate = startDate.strip().split(',')
Year = int(NewDate[0])
Month = int(NewDate[1])
Day = int(NewDate[2])
NewDate = (Year, Month, Day)
except:
print "That is invalid input."
else:
validSyntax = True
print" ok got it"
if validSyntax == True:
for line in testDate:
line = line.strip().split(',')
yearTest = int(line[0])
monthTest = int(line[1])
dayTest = int(line[2])
dateTest = (yearTest, monthTest, dayTest)
if Year == yearTest:
if Month == monthTest:
if Day == dayTest:
Done = True
print "success"
To address why it isnt working currently: you never set startDate, and so the attempt to strip().split() will not work:
NewDate = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
NewDate = startDate.strip().split(',') // startDate isnt set
you can try
startDate = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
NewDate = startDate.strip().split(',')
I agree with the commenters that you could take a stab at refactoring your code to consolidate repetitive sections.
Here is a refactored version:
import time
DATE_FORMAT = '%Y,%m,%d'
def parse_date(date_str, fmt=DATE_FORMAT):
try:
return time.strptime(date_str.strip(), fmt)
except ValueError:
return None
def get_date(adj='', fmt=DATE_FORMAT, prompt='Please enter the {}date (like {}): '):
prompt = time.strftime(prompt.format(adj.strip()+' ' if adj.strip() else '', fmt))
# repeat until a valid date is entered
while True:
inp = raw_input(prompt)
res = parse_date(inp, fmt)
if res is None:
print('Invalid input')
else:
return res
def get_test_date(date, adj='', fmt=DATE_FORMAT):
return parse_date(date, fmt) or get_date(adj, fmt)
def find_date_in_file(fname, date_str='', adj=''):
test_date = get_test_date(date_str, adj)
with open(fname) as inf:
for line in inf:
if test_date == parse_date(line):
print('Found!')
return test_date
def main():
find_date_in_file('Sales.txt', '2012,01,05', 'closing')
if __name__=="__main__":
main()