怎样写精品课程网站建设,搜索引擎优化的定义是什么,哪里有广告设计制作的培训,网站seo优化排名Python操作EXCEL#xff0c;计算3万条数据的NDVI并填入
问题描述
现在是有构建好了的查找表#xff0c;不过构建了3万条数据#xff0c;在excel中手动计算每行的NDVI值太麻烦了#xff0c;也不会操作。 就试试python吧#xff0c;毕竟python自动处理大型EXCEL数据很方便…Python操作EXCEL计算3万条数据的NDVI并填入
问题描述
现在是有构建好了的查找表不过构建了3万条数据在excel中手动计算每行的NDVI值太麻烦了也不会操作。 就试试python吧毕竟python自动处理大型EXCEL数据很方便
思路
先用pd打开表格存为dataframe。然后创建一个空的列表用来存入计算好的ndvi。在第一个循环中计算每行的ndvi并添加到列表中去。然后打开原来的文件在第二个循环中对每一个指定位置逐行写入列表中对应的ndvi值。最后保存文件
源代码
import pandas as pd
# 使用python在已存在的excel数据表中的特定位置写入数据
# excel表中的行和列都是从1开始的
import openpyxl as opfilePath rC:/Users/lenovo/Desktop/lut.xlsx
def readDataFile(readPath): # readPath: 数据文件的地址和文件名try:if (readPath[-4:] .csv):dfFile pd.read_csv(readPath, header0, sep,) # 间隔符为逗号首行为标题行# dfFile pd.read_csv(filePath, headerNone, sep,) # sep: 间隔符无标题行elif (readPath[-4:] .xls) or (readPath[-5:] .xlsx): # sheet_name 默认为 0dfFile pd.read_excel(readPath,header0) # 首行为标题行# dfFile pd.read_excel(filePath, headerNone) # 无标题行elif (readPath[-4:] .dat): # sep: 间隔符header首行是否为标题行dfFile pd.read_table(readPath, sep , header0) # 间隔符为空格首行为标题行# dfFile pd.read_table(filePath,sep,,headerNone) # 间隔符为逗号无标题行else:print(不支持的文件格式。)except Exception as e:print(读取数据文件失败{}.format(str(e)))returnreturn dfFiledatareadDataFile(C:/Users/lenovo/Desktop/lut.xlsx)
print(data)
NIRdata[nir]
Rdata[r]
list[]
for i in range(len(data)):ndvi(NIR[i]-R[i])/(NIR[i]R[i])list.append(ndvi)print(list)tableAll op.load_workbook(filePath)
table1 tableAll[lut]
for i in range(len(list)):table1.cell(i2, 11, list[i])
tableAll.save(filePath)结果 注意
1、把红波段和近红波段的列名从数字改为字符r和nir因为pd的[‘’]索引方式好像不支持数字。 2、openpyxl库只支持.xlsx格式的数据 3、cell函数行列索引从1开始
代码注释
1、tableAll op.load_workbook(filePath)
使用openpyxl库中的load_workbook()方法来打开指定路径下的工作簿文件并将其赋值给变量tableAll。其中op是openpyxl库的别名或者导入的模块。
2、table1 tableAll[‘lut’]
打开工作簿文件的sheet根据自己的sheet_name来改
3、table1.cell(i2, 11, list[i])
cell函数第一个元素为指定行第二个为指定列最后一个为待写入的数据。注意此时行和列的索引都是从1开始的与dataframelen(),range()等等python常见的索引都是从0开始不同。