我正在尝试使用此脚本计算栅格的均值并将其添加到数据框。
我当时正在考虑使用os.scandir
来获取文件夹中的所有栅格文件。
栅格的名称如
如何使用os.scandir
计算所有栅格的均值并将其保存在同一数据框中?
以下代码适用于文件夹中的一个栅格:
row_list = []
# I'm guessing that should be out of the loop.
raster_path = "D:/MODIS/" # That's the folder you want to search in for raster files.
with os.scandir(raster_path) as p: # Open the folder containing the rasters as p.
for raster in p: # Get each raster in the folder.
if not raster.name.endswith(".tif"): # Only show the files whose name ends with dot tif.
raster_file = os.path.join(raster_path, raster.name) # Get the full path of the raster, you'll need it in order to open the raster file and access its data.
raster = gdal.Open(raster_file) # Open the current raster file.
# The rest is your code...
bands = raster.RasterCount
for band in range(1, bands+1):
data = raster.GetRasterBand(band).ReadAsArray().astype('float')
mean = np.mean(data[data != 0]) #calculate mean without value 0
row_list.append({
'raster': os.path.basename(raster_name),
'band': band,
'mean': mean,
'year': 2000,
})
print("Band %s: Mean = %s" % (band, round(mean, 2)))
df = pd.DataFrame(row_list)
df.to_csv('band_meanst.csv')
谢谢您的帮助。
答案 0 :(得分:0)
我没有测试此代码,但也许它可以帮助您或为您提供有关解决问题的方法。
this.activeRoute.params.subscribe(params=> console.log(params));
它应该看起来像这样。
raster_path = "D:/MODIS/"
# ...
with os.scandir(raster_path) as p:
for raster in p:
if not raster.name.startswith('.') and entry.is_file():
raster = gdal.Open(raster.name)
bands = raster.RasterCount
# ...
如果您使用的是低于3.6的Python版本(就像我一样)。 您需要更换
row_list2000 = [] # I'm guessing that should be out of the loop.
raster_path = "D:/MODIS/" # That's the folder you want to search in for raster files.
with os.scandir(raster_path) as p: # Open the folder containing the rasters as p.
for raster in p: # Get each raster in the folder.
if not raster.name.endswith(".tif"): # Only show the files whose name ends with dot tif.
raster_file = os.path.join(raster_path, raster.name)) # Get the full path of the raster, you'll need it in order to open the raster file and access its data.
raster = gdal.Open(raster_file) # Open the current raster file.
# The rest is your code...
bands = raster.RasterCount
for band in range(1, bands+1):
data = raster.GetRasterBand(band).ReadAsArray().astype('float')
mean = np.mean(data[data != 0]) #calculate mean without value 0
row_list2000.append({
'raster': os.path.basename(raster_name),
'band': band,
'mean': mean,
'year': 2000,
'date': 325,
})
print("Band %s: Mean = %s" % (band, round(mean, 2)))
与
with os.scandir(path) as p:
for f in p:
print(f.name)
否则,您会遇到for p in os.scandir(path):
print(f.name)
错误。