отлично подходит для панд, поскольку это векторизованный способ изменения столбца в зависимости от условия.
Но хотя он, похоже, отлично работает с собственными типами np, он с датами не очень хорошо сочетается.
Это отлично работает:
>>> df2 = pd.DataFrame([["a", datetime.datetime(2024,1,2)], ["b", np.nan]], columns=["name", "date"])
>>> df2
name date
0 a 2024-01-02
1 b NaT
>>> np.where(df["date"] < datetime.datetime(2024,3,1), df["date"], np.nan)
Traceback (most recent call last):
File "
", line 1, in
np.where(df["date"] < datetime.datetime(2024,3,1), df["date"], np.nan)
~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
numpy.exceptions.DTypePromotionError: The DType could not be promoted by . This means that no common DType exists for the given inputs. For example they cannot be stored in a single array unless the dtype is `object`. The full list of DTypes is: (, )
>>>
[code]np.where[/code] отлично подходит для панд, поскольку это векторизованный способ изменения столбца в зависимости от условия. Но хотя он, похоже, отлично работает с собственными типами np, он с датами не очень хорошо сочетается. Это отлично работает: [code]>>> df1 = pd.DataFrame([["a", 1], ["b", np.nan]], columns=["name", "num"]) >>> df1 name num 0 a 1.0 1 b NaN >>> np.where(df1["num"] < 2, df1["num"], np.nan) array([ 1., nan]) [/code] Но это не так: [code]>>> df2 = pd.DataFrame([["a", datetime.datetime(2024,1,2)], ["b", np.nan]], columns=["name", "date"]) >>> df2 name date 0 a 2024-01-02 1 b NaT >>> np.where(df["date"] < datetime.datetime(2024,3,1), df["date"], np.nan) Traceback (most recent call last): File " ", line 1, in np.where(df["date"] < datetime.datetime(2024,3,1), df["date"], np.nan) ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ numpy.exceptions.DTypePromotionError: The DType could not be promoted by . This means that no common DType exists for the given inputs. For example they cannot be stored in a single array unless the dtype is `object`. The full list of DTypes is: (, ) >>> [/code] Как правильно векторизовать последнюю операцию?