猿问

使用 python 根据存储在变量中的索引将计算值添加到空列

我在编程方面相对较新,这是我编写的第一个Python代码。


这是我用来计算的代码。我已经成功计算出这些值,它们可以在变量“HT”中看到。但我正在努力使用变量“ind”中的索引将其附加到“热类别”列中的数据框“民意调查”中。将值获取到列后,将其导出到 Excel 文件不会有问题。


使用此代码,我不断为整个“热类别”列中具有相同值的每个计算值获取多个数据帧,并且它不断重复另一个计算值。我认为附加到列必须基于索引一一完成,并且我必须在最后得到一个数据框,但我不确定如何。我在互联网上浏览了许多以前的问题和解决方案,但未能找到适合我的情况的解决方案。


谁能帮帮我吗?


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)

预期产出


     Temp_Avg   Heat Category

     175.77      382   

     163.59      428

     135.97      498


 and so on.....


素胚勾勒不出你
浏览 126回答 1
1回答

千巷猫影

请注意,下面各行的缩进已进行调整。&nbsp; &nbsp; #calculation&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; y=((AH-AL)+(CH-CL))*(heat-CL)&nbsp; &nbsp; except ZeroDivisionError:&nbsp; &nbsp; &nbsp; &nbsp; print ('NA')&nbsp; &nbsp; HT=int(round(y,0))&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; #trial to add the values to the column Heat Category&nbsp; &nbsp; #poll.loc[[ind], 'Heat Category'] = HT&nbsp; &nbsp; #print (poll)&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; poll['Heat Category'].iloc[i] = HT # This line was modifiedprint(poll)第二行到最后一行也被修改结果:&nbsp; &nbsp;Temp_Avg&nbsp; Heat Category0&nbsp; &nbsp; 175.77&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3117.01&nbsp; &nbsp; 163.59&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 694.02&nbsp; &nbsp; 135.97&nbsp; &nbsp; &nbsp; &nbsp; 11297.03&nbsp; &nbsp; 124.88&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;9646.0
随时随地看视频慕课网APP

相关分类

Python
我要回答