操作EXCEL计算3万条数据的NDVI并填入

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 op

filePath = r"C:/Users/lenovo/Desktop/lut.xlsx"
def readDataFile(readPath):  # readPath: 数据文件的地址和文件名
    try:
        if (readPath[-4:] == ".csv"):
            dfFile = pd.read_csv(readPath, header=0, sep=",")  # 间隔符为逗号,首行为标题行
            # dfFile = pd.read_csv(filePath, header=None, sep=",")  # sep: 间隔符,无标题行
        elif (readPath[-4:] == ".xls") or (readPath[-5:] == ".xlsx"):  # sheet_name 默认为 0
            dfFile = pd.read_excel(readPath,header=0)  # 首行为标题行
            # dfFile = pd.read_excel(filePath, header=None)  # 无标题行
        elif (readPath[-4:] == ".dat"):  # sep: 间隔符,header:首行是否为标题行
            dfFile = pd.read_table(readPath, sep=" ", header=0)  # 间隔符为空格,首行为标题行
            # dfFile = pd.read_table(filePath,sep=",",header=None) # 间隔符为逗号,无标题行
        else:
            print("不支持的文件格式。")
    except Exception as e:
        print("读取数据文件失败:{}".format(str(e)))
        return
    return dfFile

data=readDataFile('C:/Users/lenovo/Desktop/lut.xlsx')
print(data)
NIR=data['nir']
R=data['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(i+2, 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(i+2, 11, list[i])

cell函数第一个元素为指定行,第二个为指定列,最后一个为待写入的数据。注意此时行和列的索引都是从1开始的,与dataframe,len(),range()等等python常见的索引都是从0开始不同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海绵波波107

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值