IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed

import h5py
import numpy as np
import os
from numpy import array
import matplotlib.pyplot as plt


folder_path=r'C:\Users\rahul\Downloads\OLR files-20240305T163330Z-001\OLR files'
os.chdir(folder_path)

t1=os.listdir(folder_path)
file_path = os.path.join(folder_path, t1[0])

d1 = 'Latitude'
d2 = 'Longitude'
hf=h5py.File(file_path, 'r')
lat1 = hf.get(d1)
lat1 = np.array(lat1)
lat1 = np.where(lat1==32767, np.nan, lat1)
lat1=lat1*0.01
lat2 = hf.get(d2)
lat2 = np.array(lat2)
lat2 = np.where(lat2==32767, np.nan, lat2)
lat2=lat2*0.01


a = []

for file_name in os.listdir(folder_path):
    if file_name.endswith('.h5'):
        file_path = os.path.join(folder_path, file_name)

        # Import and process the data
        hf=h5py.File(file_path, 'r')
        dataset_name = 'OLR'  
        n1 = hf.get(dataset_name)
        n1 = np.array(n1)
        n1[n1==-999]=np.nan
        n1=n1[0,:,:]
        a.append(n1)
        del n1
        
        print(f"Processed data from: {file_name}")
       
ak=np.array(a)
kkk=np.nanmean(ak,axis=0)
kkk2 = kkk[0, :, :]
fig=plt.figure(figsize = (10,9))
ax = plt.axes()

ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_title('Outgoing longwave radiation');
cs = plt.contourf(lat2,lat1, kkk2, cmap=plt.cm.Spectral_r)

plt.colorbar(cs, orientation='vertical',  shrink=0.8)

y_lim = (0,40) # latitude
x_lim = (60, 100) # longitude

plt.xlim(x_lim)
plt.ylim(y_lim)
RuntimeWarning: Mean of empty slice
  kkk=np.nanmean(ak,axis=0)
Traceback (most recent call last):
  File "c:\Users\rahul\Desktop\readhdfdata.py", line 67, in <module>
    kkk2 = kkk[0, :, :]
           ~~~^^^^^^^^^
IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed

Please Tell us what’s happening in your own words.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!

it is showing that too many indices for array: array is 2-dimensional, but 3 were indexed.

kkk2 = kkk[0, :, :] in this line
i have appended folder such that it’s file make a stack and form 3dimensional, but it is not accepting and showing error

I’m not sure I understand, or that I can reproduce without more details

what is kkk? what do you want to do with it and what do you want kkk2 to be?

kkk is mean of all the files

Can you print this variable and show what it contains?

You could also consider a more descriptive variable name like “mean_value”

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.