批量栅格分组均值计算无结果输出问题排查求助
Troubleshooting & Solution for Your Raster Averaging Task
Hey there! Let's break down why your code might be running without errors but producing no output, then walk through a tested solution that fits your exact needs.
Common Issues to Check First
- File Path Problems: Double-check that your input raster paths are pointing to the right folder, and that your output directory exists (and you have write access to it). If the output folder doesn't exist, many raster libraries will silently fail to save files without throwing an error.
- Flawed Grouping Logic: With 28 rasters, getting 9 output grids means your grouping needs to be precise:
- Group 1: Rasters 1–3
- Groups 2–8: Rasters 4–6, 7–9, ..., 22–24
- Group 9: Rasters 25–28 (since 3 + 7*3 + 4 = 28)
If your code's grouping skips intended rasters or doesn't cover all 9 groups, you might get fewer outputs than expected (or none at all).
- Missing Save Step: It's easy to forget the final step of writing the averaged array to a new raster file—even if all calculations run, no file gets saved without this critical step.
Example Working Code (Using Rasterio)
Here's a Python script that handles grouping, averaging, and naming correctly. First, make sure you have rasterio and numpy installed (pip install rasterio numpy).
import os import numpy as np import rasterio # Configuration - update these paths to match your setup input_folder = "path/to/your/raster/folder" output_folder = "path/to/your/output/folder" base_output_name = "Tmin-2010-" date_suffixes = ["01-15", "02-15", "03-15", "04-15", "05-15", "06-15", "07-15", "08-15", "09-15"] # Create output folder if it doesn't exist (prevents silent failures) os.makedirs(output_folder, exist_ok=True) # Get sorted list of raster files (order matters!) all_rasters = sorted([f for f in os.listdir(input_folder) if f.endswith(('.tif', '.tiff'))]) if len(all_rasters) != 28: print(f"Warning: Found {len(all_rasters)} rasters instead of 28. Adjust grouping if needed.") # Define the 9 groups as per your requirement raster_groups = [] raster_groups.append(all_rasters[0:3]) # Group 1: first 3 rasters # Groups 2-8: next 7 sets of 3 rasters for i in range(3, 25, 3): raster_groups.append(all_rasters[i:i+3]) # Group 9: remaining 4 rasters (25-28) raster_groups.append(all_rasters[25:]) # Process each group to compute and save the mean for group_idx, raster_group in enumerate(raster_groups): if group_idx >= len(date_suffixes): break # Stop if we run out of date names # Read all rasters in the current group raster_arrays = [] output_profile = None for raster_file in raster_group: full_path = os.path.join(input_folder, raster_file) with rasterio.open(full_path) as src: # Copy metadata from the first raster in the group if output_profile is None: output_profile = src.profile # Read the first band (adjust if your rasters use multiple bands) arr = src.read(1) # Replace NoData values with NaN for correct mean calculation arr[arr == src.nodata] = np.nan raster_arrays.append(arr) # Calculate the mean (ignores NaN/NoData values) mean_array = np.nanmean(raster_arrays, axis=0) # Update output profile for float values (averages are rarely integers) output_profile.update(dtype=rasterio.float32, count=1) # Generate output filename and path output_filename = f"{base_output_name}{date_suffixes[group_idx]}.tif" output_path = os.path.join(output_folder, output_filename) # Save the mean raster with rasterio.open(output_path, 'w', **output_profile) as dst: dst.write(mean_array.astype(rasterio.float32), 1) print(f"Successfully saved: {output_filename}")
Key Fixes & Notes
- Sorted Raster List: Always sort your input files—unsorted filenames can break your grouping logic entirely.
- NoData Handling: The code replaces raster NoData values with
NaNso they don't skew the mean calculation. Adjust thesrc.nodatacheck if your rasters use a custom NoData value (like -9999). - Output Folder Creation: The
os.makedirsline ensures your output directory exists, preventing silent save failures. - Grouping Flexibility: If you intended the last group to be 3 rasters (and the 28th raster is an extra), just change the final group line to
raster_groups.append(all_rasters[24:27])and remove the 28th file.
How to Debug Your Original Code
- Add print statements to verify:
- How many rasters are being loaded (
print(len(all_rasters))) - What each group contains (
print(raster_group)for each iteration) - Whether the output path is valid (
print(output_path))
- How many rasters are being loaded (
- Check for indentation errors—sometimes the save step might be nested incorrectly and never execute.
- Verify that your averaged array isn't all
NaN(which could happen if all rasters in a group have NoData in every cell).
内容的提问来源于stack exchange,提问作者LMontef
相关产品推荐
相关产品推荐

