البرمجة

كيفية تجاهل قيم NaN وتوحيد البيانات في NumPy

To disregard NaN values and normalize the data in a NumPy array, you can achieve this in several steps. First, you need to find the indices of NaN values in the array. Then, you can apply normalization to the non-NaN values. Here’s a step-by-step guide to doing this:

  1. Import the required libraries:
python
import numpy as np from sklearn.preprocessing import StandardScaler
  1. Create a sample numpy array with NaN values:
python
data = np.array([1.0, 2.0, np.nan, 4.0, 5.0])
  1. Find the indices of NaN values:
python
nan_indices = np.isnan(data)
  1. Replace NaN values with a placeholder (e.g., 0) to allow normalization:
python
data[nan_indices] = 0
  1. Normalize the array using StandardScaler from sklearn.preprocessing:
python
scaler = StandardScaler() normalized_data = scaler.fit_transform(data.reshape(-1, 1))
  1. Replace the placeholder values with NaN in the normalized data:
python
normalized_data[nan_indices] = np.nan

Putting it all together:

python
import numpy as np from sklearn.preprocessing import StandardScaler data = np.array([1.0, 2.0, np.nan, 4.0, 5.0]) nan_indices = np.isnan(data) data[nan_indices] = 0 scaler = StandardScaler() normalized_data = scaler.fit_transform(data.reshape(-1, 1)) normalized_data[nan_indices] = np.nan print(normalized_data)

This code will normalize the non-NaN values in the array while keeping the NaN values at their original positions.

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

في الخطوة الأولى، عرفنا nan_indices باستخدام np.isnan(data)، وهي تعيد مصفوفة بولية تحتوي على True لكل موضع في data حيث تكون قيمته NaN و False لغير ذلك.

ثم، قمنا بتعويض القيم NaN في data بقيمة بديلة (هنا استخدمنا 0) باستخدام data[nan_indices] = 0، وهذا يسمح لنا بتطبيق التوحيد على القيم غير NaN.

في الخطوة الأخيرة، قمنا بإعادة تعيين القيم NaN في البيانات الموحدة باستخدام normalized_data[nan_indices] = np.nan لكي تعود قيم NaN إلى مواضعها الأصلية.

يرجى ملاحظة أن هذا النهج يفترض أنك تريد استبقاء NaN في المواقع الأصلية بعد التوحيد. إذا كنت ترغب في استبدال NaN بقيمة معينة بدلاً من الاحتفاظ بها كما هي، يمكنك استخدام معالجة بيانات مختلفة، مثل تعويض NaN بالمتوسط أو الوسيط قبل التوحيد.

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