I'm trying to do some calculations in python using an excel with several rows and using 3 columns. I'm using the columns 'Band' and 'Antenna_Heigh' and I would like to save these values in the column 'Colors'. My code looks like this but I have an error saying 'list assignment index out of range'.
madrid = pd.read_excel('Madrid.xlsx')
ch = []
d=[]
L = 8.4
for i in range(0, len(madrid)):
ch[i] = 0.8 (1.1*math.log10(madrid['Band'][i]) - 0.7)*madrid['Antenna_Height'][i] - 1.56*math.log10(madrid['Band'][i])
d[i] = ((L - 69.55 - 26.16*math.log10(madrid['Band'][i]) 13.82*math.log10(madrid['Antenna_Height'][i]) ch[i])/(44.9 - 6.55*math.log10(madrid['Antenna_Height'][i])))**10
madrid['Colors'][i] = d[i]
CodePudding user response:
The list ch
is empty, so calling any element index like ch[0]
or ch[1]
will result in error "list index out of range"
I see you're trying to append to the various lists. You can try (but I'm not sure about the formula, please check them)
import math
madrid = pd.read_excel('Madrid.xlsx')
ch = []
d=[]
L = 8.4
for i in range(0, len(madrid)):
ch_temp = 0.8 (1.1*math.log10(madrid['Band'][i]) - 0.7)*madrid['Antenna_Height'][i] - 1.56*math.log10(madrid['Band'][i])
ch.append(ch_temp)
d_temp = ((L - 69.55 - 26.16*math.log10(madrid['Band'][i]) 13.82*math.log10(madrid['Antenna_Height'][i]) ch[i])/(44.9 - 6.55*math.log10(madrid['Antenna_Height'][i])))**10
d.append(d_temp)
madrid['Colors'][i] = d[i]
print(madrid)
Output:
Band Antenna_Height Colors
0 1 3 18.262619
1 2 3 62.881852
2 3 3 121.442224
3 4 3 188.948366
4 5 3 262.794745
5 6 3 341.404788
CodePudding user response:
The pandas' way of applying a function to many rows is with pd.apply
. I'm using index=1
to get the values horizontally through both columns 'Antenna_Height' and 'Band':
def get_color(row):
L = 8.4
ch = 0.8 (1.1*math.log10(row['Band']) - 0.7)*row['Antenna_Height'] - 1.56*math.log10(row['Band'])
d = ((L - 69.55 - 26.16*math.log10(row['Band']) 13.82*math.log10(row['Antenna_Height']) ch)/(44.9 - 6.55*math.log10(row['Antenna_Height'])))**10
return d
madrid['Color'] = madrid.apply(get_color, axis = 1)
This is not necessarily faster, but in general makes the intention of the code more obvious.