# How to calculate mean for each band in raster using GDAL and Python 3

I have a raster with 6 bands and I need to calculate the mean for all bands in the raster without value 0

I have this script but it works for one band only:

``````import os
from osgeo import gdal
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import ogr

raster = gdal.Open("D:/script/NDVI2015.tif")
bands = raster.RasterCount
bands
6

geotransform = raster.GetGeoTransform()
proj= raster.GetProjection()
meandata(2) = np.mean(data[data != 0])#calcul mean without value 0
``````

I'm very new with Python and GDAL.

Building on @Luke's comment, incorporate the band number into a `for` loop using `range()`:

``````import gdal
import numpy as np

raster = gdal.Open(r'/path/to/your/image.tif')
bands = raster.RasterCount

for band in range(1, bands+1):
• what is 2 in last line `print("Band %s: Mean = %s" % (band, round(mean, 2)))` ? ( mean,2) Jan 16, 2019 at 15:47
• your code is fonction for me and i have this result: `Band 1: Mean = 1712.83 Band 2: Mean = 1803.14 Band 3: Mean = 1662.33 Band 4: Mean = 1868.77 Band 5: Mean = 1900.97 Band 6: Mean = 2031.13` thank you , but please how can i save the value of mean for all bands in dataframe ? Jan 16, 2019 at 15:58