البرمجة

كيفية العثور على مواقع القيم NaN في مصفوفة NumPy

To get the indices of all NaN values in a NumPy array, you can use the np.where function. Here’s how you can do it:

python
import numpy as np # Define the array arr = np.array([[1, 2, 3, 4], [2, 3, np.nan, 5], [np.nan, 5, 2, 3]]) # Find indices of NaN values indices = np.where(np.isnan(arr)) # Convert indices to a list of tuples indices_list = list(zip(indices[0], indices[1])) print(indices_list)

This will output:

css
[(1, 2), (2, 0)]

Here’s a breakdown of the code:

  1. Import the NumPy library as np.
  2. Define the array arr.
  3. Use np.isnan(arr) to create a boolean mask of NaN values in the array.
  4. Use np.where to get the indices where the mask is True.
  5. Convert the indices to a list of tuples using zip.
  6. Print the list of indices.

المزيد من المعلومات

بالطبع! في هذا السياق، يمكننا استخدام np.argwhere بدلاً من np.where للحصول على نفس النتيجة. تختلف الاختلافات بينهما في تنسيق الإخراج فقط، حيث يقوم np.argwhere بإرجاع مصفوفة 2D تحتوي على الفهرس المطلوب للقيم NaN. اليك الكود:

python
import numpy as np # تعريف المصفوفة arr = np.array([[1, 2, 3, 4], [2, 3, np.nan, 5], [np.nan, 5, 2, 3]]) # الحصول على الفهارس للقيم NaN indices = np.argwhere(np.isnan(arr)) # تحويل الفهارس إلى قائمة من الأزواج indices_list = [tuple(idx) for idx in indices] print(indices_list)

هذا سيعيد نفس النتيجة:

css
[(1, 2), (2, 0)]

يمكن استخدام أي من الطريقتين (np.where أو np.argwhere) وفقًا لتفضيلاتك الشخصية.

مقالات ذات صلة

زر الذهاب إلى الأعلى

هذا المحتوى محمي من النسخ لمشاركته يرجى استعمال أزرار المشاركة السريعة أو تسخ الرابط !!