البرمجة
كيفية العثور على مواقع القيم NaN في مصفوفة NumPy
02/03/2024آخر تحديث: 02/03/2024
4 دقيقة واحدة
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:
pythonimport 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:
- Import the NumPy library as np.
- Define the array
arr
. - Use
np.isnan(arr)
to create a boolean mask of NaN values in the array. - Use
np.where
to get the indices where the mask is True. - Convert the indices to a list of tuples using
zip
. - Print the list of indices.
المزيد من المعلومات
بالطبع! في هذا السياق، يمكننا استخدام np.argwhere
بدلاً من np.where
للحصول على نفس النتيجة. تختلف الاختلافات بينهما في تنسيق الإخراج فقط، حيث يقوم np.argwhere
بإرجاع مصفوفة 2D تحتوي على الفهرس المطلوب للقيم NaN. اليك الكود:
pythonimport 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
) وفقًا لتفضيلاتك الشخصية.