I am trying to delete the last item in both the rows and columns in my numpy.ndarray
(type = class numpy.ndarray
). My array has 30 rows and 180 columns (i.e. 180 values per row). I have tried numpy.delete
but this simply removes the whole row/column.
To illustrate what I want to achieve I created the following example in Python using and array and nested for loops:
a = np.array([[[1,2,3,4,5,6],[1,2,3,4],[1,2,3,4]],[[1,2,3,4,5,6],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]],[[1,2,3,4],[1,2,3,4]]])
for list in a:
for sublist in list:
del sublist[-1]
Using
print(a)
Gives the following array:
[[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4]] [[1, 2, 3, 4], [1, 2, 3, 4]]]
Using
print(list)
after the for loops gives:
[[1, 2, 3, 4, 5], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3, 4, 5], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3]]
Unfortunately using this on my array gives the following error:
TypeError: 'numpy.float64' object does not support item deletion
Thanks
Update:
I am extracting my information from a grid NetCDF file. I have changed the word list
to l
since list
is a Python keyword. This didn't change it for me.
This provides a good example of my array:
c = np.arange(5400).reshape(30,180)
for l in c:
for i in l:
del i[-1]
When I run this code I get the following error:
Traceback (most recent call last): File "main.py", line 18, in <module>
del i[-1]
TypeError: 'numpy.int64' object does not support item deletion