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

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

问题描述

现在是有构建好了的查找表,不过构建了3万条数据,在excel中手动计算每行的NDVI值太麻烦了,也不会操作。

就试试python吧,毕竟python自动处理大型EXCEL数据很方便

思路

先用pd打开表格,存为dataframe。然后创建一个空的列表用来存入计算好的ndvi。在第一个循环中,计算每行的ndvi,并添加到列表中去。然后打开原来的文件,在第二个循环中,对每一个指定位置逐行写入列表中对应的ndvi值。最后保存文件

源代码

python 复制代码
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开始不同。

相关推荐
ejinxian8 分钟前
PHP 超文本预处理器 发布 8.5 版本
开发语言·php
czhc11400756639 分钟前
Linux 76 rsync
linux·运维·python
软件黑马王子34 分钟前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon35 分钟前
C#读写文件:多种方式详解
开发语言·数据库·c#
悠悠小茉莉40 分钟前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
全干engineer40 分钟前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Da_秀44 分钟前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte1 小时前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
m0_625686551 小时前
day53
python
Real_man1 小时前
告别 requirements.txt,拥抱 pyproject.toml和uv的现代Python工作流
python