From 73ad033aa1a33e7a87a6a2ac1549be899118f073 Mon Sep 17 00:00:00 2001 From: "Ankit.Ahlawat@ibm.com" Date: Tue, 22 Jul 2025 10:50:20 +0530 Subject: [PATCH 1/2] FIX: handle insertion of 0-dim datetime64 arrays into string scalars in np.insert (#29339) - Fix np.insert to correctly convert 0-dim np.datetime64 arrays to strings when inserting into string arrays. This resolves RuntimeError when inserting datetime64 wrapped in 0-d arrays. --- numpy/lib/_function_base_impl.py | 9 ++++++++- numpy/lib/tests/test_function_base.py | 7 +++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py index f5690a829fc6..80ce5cfd75de 100644 --- a/numpy/lib/_function_base_impl.py +++ b/numpy/lib/_function_base_impl.py @@ -5612,7 +5612,14 @@ def insert(arr, obj, values, axis=None): f"with size {N}") if (index < 0): index += N - + # np.insert fails with datetime64 and string input combination #29339 + if isinstance(values, np.ndarray): + if np.issubdtype(values.dtype, np.datetime64) and \ + np.issubdtype(arr.dtype, np.str_): + if values.ndim == 0: + values = values.item() + else: + values = values.astype(str) # There are some object array corner cases here, but we cannot avoid # that: values = array(values, copy=None, ndmin=arr.ndim, dtype=arr.dtype) diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 37f8bbadc31a..6b30b49a0545 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -1344,6 +1344,13 @@ def test_return_type(self): res = np.gradient(([1, 2], [2, 3])) assert type(res) is tuple + def test_insert_0d_datetime64_into_string_scalar(self): + # np.insert fails with datetime64 and string input combination #29339 + arr = '5' + val_0d = np.array(np.datetime64('2025-10-10')) # 0-d array + result_0d = np.insert(arr, 0, val_0d) + expected_0d = np.array(['2025-10-10', '5'], dtype=' Date: Tue, 22 Jul 2025 11:50:45 +0530 Subject: [PATCH 2/2] fix test issue --- numpy/lib/tests/test_function_base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 6b30b49a0545..542461d59229 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -1349,7 +1349,7 @@ def test_insert_0d_datetime64_into_string_scalar(self): arr = '5' val_0d = np.array(np.datetime64('2025-10-10')) # 0-d array result_0d = np.insert(arr, 0, val_0d) - expected_0d = np.array(['2025-10-10', '5'], dtype=' pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy