Skip to content

[python][RDF] Handle the creation of an empty RDataFrame in _MakeNumpyDataFrame #18585

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ def pypowarray(numpyvec, pow):

\endpythondoc
'''
import sys

from . import pythonization
from ._pyz_utils import MethodTemplateGetter, MethodTemplateWrapper

Expand Down Expand Up @@ -246,18 +246,18 @@ def RDataFrameAsNumpy(df, columns=None, exclude=None, lazy=False):

# Early check for numpy
try:
import numpy
except:
import numpy # noqa: F401
except ImportError:
raise ImportError("Failed to import numpy during call of RDataFrame.AsNumpy.")

# Find all column names in the dataframe if no column are specified
if not columns:
columns = [str(c) for c in df.GetColumnNames()]

# Exclude the specified columns
if exclude == None:
if exclude is None:
exclude = []
columns = [col for col in columns if not col in exclude]
columns = [col for col in columns if col not in exclude]

# Register Take action for each column
result_ptrs = {}
Expand Down Expand Up @@ -321,6 +321,7 @@ def GetValue(self):

if self._py_arrays is None:
import numpy

from ROOT._pythonization._rdf_utils import ndarray

# Convert the C++ vectors to numpy arrays
Expand Down Expand Up @@ -474,7 +475,7 @@ def pythonize_rdataframe(klass):

klass._OriginalFilter = klass.Filter
klass._OriginalDefine = klass.Define
from ._rdf_pyz import _PyFilter, _PyDefine
from ._rdf_pyz import _PyDefine, _PyFilter

klass.Filter = _PyFilter
klass.Define = _PyDefine
Expand All @@ -487,10 +488,16 @@ def _make_name_rvec_pair(key, value):
if not isinstance(key, str):
raise RuntimeError("Object not convertible: Dictionary key is not convertible to a string.")

# Convert value to RVec and attach to dictionary
pyvec = ROOT.VecOps.AsRVec(value)
if not pyvec:
raise RuntimeError("Object not convertible: Dictionary entry " + key + " is not convertible with AsRVec.")
try:
# Convert value to RVec and attach to dictionary
pyvec = ROOT.VecOps.AsRVec(value)
except TypeError as e:
if "Cannot create an RVec from a numpy array of data type object" in str(e):
raise RuntimeError(
f"Failure in creating column '{key}' for RDataFrame: the input column type is 'object', which is not supported. Make sure your column type is supported."
) from e
else:
raise

# Add pairs of column name and associated RVec to signature
return ROOT.std.pair["std::string", type(pyvec)](key, ROOT.std.move(pyvec))
Expand Down
20 changes: 20 additions & 0 deletions bindings/pyroot/pythonizations/test/rdataframe_makenumpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,26 @@ def test_object_dtype_strings(self):
entries = df.AsNumpy()["x"]
self.assertTrue(np.array_equal(entries, np.array(["test_string_1", "test_string_2"], dtype=object)))

def test_empty_arrays(self):
"""
Test creating an RDataFrame from an empty numpy array with different data types
"""
for dtype in self.dtypes:
data = {"x": np.array([], dtype=dtype)}
df = ROOT.RDF.FromNumpy(data)
colnames = df.GetColumnNames()
self.assertIn("x", colnames)
self.assertEqual(df.Count().GetValue(), 0)

data_obj = {"x": np.array([], dtype="object")}
with self.assertRaises(RuntimeError) as context:
df = ROOT.RDF.FromNumpy(data_obj)

self.assertIn(
"Failure in creating column 'x' for RDataFrame: the input column type is 'object', which is not supported. Make sure your column type is supported",
str(context.exception),
)

def test_multiple_columns(self):
"""
Test reading multiple columns
Expand Down
Loading