Python Forum
IndexError: index 31 is out of bounds for axis 0 with size 31
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IndexError: index 31 is out of bounds for axis 0 with size 31
#1
Hi all,

I try to convert a netCDF to XML with the following lines of code, and I think the code handle the bounds issue. However, it still shows the error message: IndexError: index 31 is out of bounds for axis 0 with size 31

My code:

import netCDF4 as nc
from pykml.factory import KML_ElementMaker as KML
from lxml import etree

# Define input and output file paths
input_file = 'C:/Users/asus/.spyder-py3/CarbonMonitor_0_Power_y2019_m01.nc'
output_kml_file = 'carbon_monitor_emissions.kml'

# Open the NetCDF file
ds = nc.Dataset(input_file)

# Extract latitude, longitude, and emission data
latitudes = ds.variables['latitude'][:]
longitudes = ds.variables['longitude'][:]
emissions = ds.variables['emission'][:, :, :]  # [lon, lat, day]

# Ensure bounds don't exceed lat/lon limits
lat_size = len(latitudes)
lon_size = len(longitudes)
num_days = emissions.shape[2]  # Number of days in the data

# Create KML structure
kml_doc = KML.kml(
    KML.Document(
        KML.name("CO2 Emissions Data"),
    )
)

# Convert emissions to KML format
for day in range(num_days):
    for lat_idx in range(lat_size):
        for lon_idx in range(lon_size):
            try:
                emission_value = emissions[lon_idx, lat_idx, day]

                if not emission_value is None and not isinstance(emission_value, float):  # Skip if NaN
                    lat = latitudes[lat_idx]
                    lon = longitudes[lon_idx]

                    # Create a Placemark for each emission data point
                    placemark = KML.Placemark(
                        KML.name(f"Emission Day {day+1}"),
                        KML.Point(
                            KML.coordinates(f"{lon},{lat}")
                        ),
                        KML.description(f"Emission: {emission_value} kgC/h"),
                    )
                    kml_doc.Document.append(placemark)
            except IndexError:
                # Handle any potential indexing errors
                print(f"Index error at day {day}, lat {lat_idx}, lon {lon_idx}")
                continue

# Save KML file
with open(output_kml_file, 'w') as f:
    f.write(etree.tostring(kml_doc, pretty_print=True).decode('utf-8'))

print(f"KML file saved to {output_kml_file}")
Gribouillis write Sep-21-2024, 09:38 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Can you ask Python to print the shapes of latitudes, longitudes and emissions? Also please post complete traceback.
« We can solve any problem by introducing an extra level of indirection »
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  IndexError: index 10 is out of bounds for axis 0 with size 10 Mehboob 11 9,058 Sep-14-2023, 06:54 AM
Last Post: Mehboob
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 13,510 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  IndexError: list index out of range dolac 4 3,298 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 2,184 May-03-2022, 01:39 PM
Last Post: Anldra12
  For loop index out of bounds armitron121 2 4,088 Feb-08-2022, 04:23 PM
Last Post: armitron121
  Sample labels from excel file in order to put them on x-axis and y-axis of a plot hobbyist 11 6,717 Sep-14-2021, 08:29 AM
Last Post: hobbyist
  IndexError: list index out of range rf_kartal 6 4,450 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  IndexError: list index out of range Laplace12 1 2,785 Jun-22-2021, 10:47 AM
Last Post: Yoriz
  IndexError: list index out of range brunolelli 11 12,462 Mar-25-2021, 11:36 PM
Last Post: brunolelli
  IndexError: list index out of range ramu4651 2 4,644 Jan-24-2021, 01:45 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020