I am relatively new in programming and this is the first python code I have made.
This is a code I used for calculation. I have managed to calculate the values and they can be seen in the variable "HT". But I am struggling with appending it to the Dataframe "poll" in the "Heat Category" column using the index in the variable "ind". After getting the values to the column, I won't have a problem exporting it to excel file.
With this code, I keep getting multiple data frames for each calculated value with the same value throughout the "Heat Category" column, and it keeps repeating for another calculated value. I think the appending to the column must be done one-by-one based on the index, and I must get a single data frame at the end but I am not sure how. I have looked through many previous questions and solutions on the internet, but I have failed to find a solution for my case.
Can anyone please help me?
import pandas as pd
#assigning range
AHi =[50,100,150,200,300]
ALo=[0,51,101,151,201]
CHi=[20,40,60,160,260]
CLo=[0,20.1,40.1,60.1,160.1]
poll=pd.read_excel("C:/Compiled sheet.xlsx")
x = poll[['Temp_Avg']]
y = poll[['Heat Category']]
x_num=len(x)
print(x_num)
i=0
for i in range(x_num):
heat = x.iloc[i]['Temp_Avg'] #extracting all data from the column Temp_Avg
len_num=0
len_num=len(AHi)
for j in range(len_num):
if heat<CHi[j] and heat>=CLo[j]: #finding out the range in which the values lie
z=(CLo[j])
ind=CLo.index(z) #finding out the index
CH=CHi[ind]
CL=CLo[ind]
AH=AHi[ind]
AL=ALo[ind]
#calculation
try:
y=((AH-AL)+(CH-CL))*(heat-CL)
except ZeroDivisionError:
print ('NA')
HT=int(round(y,0))
#trial to add the values to the column Heat Category
#poll.loc[[ind], 'Heat Category'] = HT
#print (poll)
poll.loc[:,'Heat Category'] = HT
print(poll)
Expected output
Temp_Avg Heat Category
175.77 382
163.59 428
135.97 498
and so on.....
please note the indentations on the lines below were adjusted.
#calculation
try:
y=((AH-AL)+(CH-CL))*(heat-CL)
except ZeroDivisionError:
print ('NA')
HT=int(round(y,0))
#trial to add the values to the column Heat Category
#poll.loc[[ind], 'Heat Category'] = HT
#print (poll)
poll['Heat Category'].iloc[i] = HT # This line was modified
print(poll)
also the 2nd to the last line was modified
result:
Temp_Avg Heat Category
0 175.77 3117.0
1 163.59 694.0
2 135.97 11297.0
3 124.88 9646.0
and so on...