python - 使用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.....
解决方案
请注意以下行的缩进已调整。
#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)
还修改了第二行到最后一行
结果:
Temp_Avg Heat Category
0 175.77 3117.0
1 163.59 694.0
2 135.97 11297.0
3 124.88 9646.0
等等...
推荐阅读
- python-3.x - Python3 文件解析 - 重新打开文件?
- c - 如何在 macOS 上找到 C 头文件 errno.h 的位置?
- mysql - MySQL Docker 容器如果不存在则创建数据库
- xcode - 在 Info.plist 中将 Export Compliance 声明为 false 不会绕过 App Store Connect 上的提交过程
- ruby-on-rails - NoMethodError (undefined method `[]' for nil:NilClass): Ruby on Rails 即使使用 dig
- c - 这个带有两个递归调用的返回语句是如何工作的?
- c - 无法理解如何设置位
- javascript - 为什么只是通过?我想知道更多我需要解释
- node.js - NPM 安装失败了几个 ENOENT
- java - 在一个 Kafka Topic 下发送两个 Serialized Java 对象