NumPy array को आप , simply python for loop की help से iterate कर सकते हैं। हालाँकि ndarray Object हमें कुछ अलग methods भी provide करता है , जो array को need के according iterate करने में help करते हैं।

What is iterating ?

iterating का actually मतलब होता है array के हर एक elements को visit करना।

NumPy Array Iteration Example

Copy Fullscreen Close Fullscreen Run
#import numpy module.
import numpy as np
arr = np.array([12,23,34,45,56,56])
for item in arr : print(item)
Output
C:\Users\Rahulkumar\Desktop\python>python module_numpy.py
12
23
34
45
56
56

तो कुछ इस तरह से array को iterate करते हैं , हालाँकि यह तो एक simple 1 - dimensional array था इसलिए हमें direct values मिली अगर multi - dimensional होता तो हमें value की जगह एक array elements मिलते।

Iterating multi - dimensional array

Copy Fullscreen Close Fullscreen Run
import numpy as np
#now let's take two dimensioanl array.
arr = np.array([ [12,23,34], [45,56,56], [12,23,23]])
for item_arr in arr : print(item_arr)

#you may also use inner loop to iterate every element.
for item_arr in arr : 
    for item in item_arr :
        print(item, end=", ")
    
    #use line break.
    print('');
Output
C:\Users\Rahulkumar\Desktop\python>python module_numpy.py
12, 23, 34, 
45, 56, 56, 
12, 23, 23,

numPy Iteration Using ndenumerate()

ऊपर दिए गए example में एक problem थी, कि हमें अगर किसी element का index नहीं पता होता है , इसके लिए हम ndarray object का ndenumerate() method use करते हैं। जो हमें current element का index tuple provide करता है।

Why tuple ?

tupleइसलिए provide करता है ताकि , multidimensional array में भी हर element की exact index पता चल सके।

See Example :

Copy Fullscreen Close Fullscreen Run
import numpy as np
#take two dimensioanl array.
arr = np.array([ [12,23,34], [45,56,56], [12,23,23]])
for item_arr, index_tuple in np.ndenumerate(arr) : 
    print(index_tuple, ' : ' ,item_arr)
Output
C:\Users\Rahulkumar\Desktop\python>python module_numpy.py
12  :  (0, 0)
23  :  (0, 1)
34  :  (0, 2)
45  :  (1, 0)
56  :  (1, 1)
56  :  (1, 2)
12  :  (2, 0)
23  :  (2, 1)
23  :  (2, 2)

ध्यान रहें ndenumerate() method का use करने पर हम multi - dimensional array का भी हर एक value ही visit कर रहे होते हैं , no matter वो कितने dimension का array है। जैसा कि आप example में देख सकते हैं , कि single for loop से ही 2 dimensional array के हर एक element visit हुआ है।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers