Skip to content
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

ENH: Allow genfromtxt to unpack structured arrays #16650

Merged
merged 13 commits into from Sep 11, 2020
10 changes: 10 additions & 0 deletions doc/release/upcoming_changes/16650.compatibility.rst
@@ -0,0 +1,10 @@
`np.genfromtxt` now correctly unpacks structured arrays
-------------------------------------------------------------------------
Previously, `genfromtxt` failed to unpack if it was called with ``unpack=True``
and a structured datatype was inferred or passed to the ``dtype`` argument.

Structured arrays will now correctly unpack into a list of arrays,
one for each column::

>>> np.genfromtxt(StringIO("1 2.0 \n 3 4.0"), unpack=True)
[array([1, 3]), array([2., 4.])]]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this example requires a structured dtype= being passed in? It may be good to point/show an example which triggers the changed behaviour without passing in dtype= (if that is possible).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(i.e. I tried the example on this branch, and the behaviour is not as written here – also there is an additional closing bracket)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry about that, it looks like the numbers in my example were too small so the inferred dtype was '<u4'. I replaced it with the test case for dtype=None.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe I have to take a closer look at the tests, or am I running the wrong code? But it seems to me that this gives:

In [2]: from io import StringIO
In [3]: np.genfromtxt(StringIO("21 58.0 \n 35 72.0"), unpack=True)
Out[3]: 
array([[21., 35.],
       [58., 72.]])

OTOH, this one changed behaviour as expected:

In [5]: np.genfromtxt(StringIO("21 58.0 \n 35 72.0"), unpack=True, dtype="i,d")

so, right now I think the example is still incorrect, and if there are tests for this, they should probably be refined to check that the result is (correctly, I assume) a single array in the first case, since it should be a single array when there is no structured dtype detected (which seems to be the default?).

Unless this should change and I am missing something?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope, you were running the right code; it turns out that the example was incorrect. I forgot that detection of a structured dtype relies on passing dtype=None to override the default dtype=float (otherwise, a single array is the correct return value). My example in the release note failed to specify the dtype argument. Should be correct now.

22 changes: 17 additions & 5 deletions numpy/lib/npyio.py
Expand Up @@ -837,8 +837,9 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None,
fourth column the same way as ``usecols = (3,)`` would.
unpack : bool, optional
If True, the returned array is transposed, so that arguments may be
unpacked using ``x, y, z = loadtxt(...)``. When used with a structured
data-type, arrays are returned for each field. Default is False.
unpacked using ``x, y, z = loadtxt(...)``. When used with a
structured data-type, arrays are returned for each field.
Default is False.
ndmin : int, optional
The returned array will have at least `ndmin` dimensions.
Otherwise mono-dimensional axes will be squeezed.
Expand Down Expand Up @@ -1631,7 +1632,9 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
If 'lower', field names are converted to lower case.
unpack : bool, optional
If True, the returned array is transposed, so that arguments may be
unpacked using ``x, y, z = loadtxt(...)``
unpacked using ``x, y, z = genfromtxt(...)``. When used with a
structured data-type, arrays are returned for each field.
Default is False.
usemask : bool, optional
If True, return a masked array.
If False, return a regular array.
Expand Down Expand Up @@ -2242,9 +2245,18 @@ def encode_unicode_cols(row_tup):
if usemask:
output = output.view(MaskedArray)
output._mask = outputmask
output = np.squeeze(output)
if unpack:
return output.squeeze().T
return output.squeeze()
if names is None:
return output.T
elif len(names) == 1:
# squeeze single-name dtypes too
return output[names[0]]
mattip marked this conversation as resolved.
Show resolved Hide resolved
else:
# For structured arrays with multiple fields,
# return an array for each field.
return [output[field] for field in names]
return output


def ndfromtxt(fname, **kwargs):
Expand Down
47 changes: 46 additions & 1 deletion numpy/lib/tests/test_io.py
Expand Up @@ -1011,7 +1011,7 @@ def test_empty_field_after_tab(self):
a = np.array([b'start ', b' ', b''])
assert_array_equal(x['comment'], a)

def test_structure_unpack(self):
def test_unpack_structured(self):
txt = TextIO("M 21 72\nF 35 58")
dt = {'names': ('a', 'b', 'c'), 'formats': ('|S1', '<i4', '<f4')}
a, b, c = np.loadtxt(txt, dtype=dt, unpack=True)
Expand Down Expand Up @@ -2343,6 +2343,51 @@ def test_auto_dtype_largeint(self):
assert_equal(test['f1'], 17179869184)
assert_equal(test['f2'], 1024)

def test_unpack_structured(self):
# Regression test for gh-4341
# Unpacking should work on structured arrays
txt = TextIO("M 21 72\nF 35 58")
dt = {'names': ('a', 'b', 'c'), 'formats': ('|S1', '<i4', '<f4')}
a, b, c = np.genfromtxt(txt, dtype=dt, unpack=True)
assert_(a.dtype.str == '|S1')
assert_(b.dtype.str == '<i4')
assert_(c.dtype.str == '<f4')
assert_array_equal(a, np.array([b'M', b'F']))
assert_array_equal(b, np.array([21, 35]))
assert_array_equal(c, np.array([72., 58.]))

def test_unpack_auto_dtype(self):
# Regression test for gh-4341
# Unpacking should work when dtype=None
txt = TextIO("M 21 72.\nF 35 58.")
expected = (np.array(["M", "F"]), np.array([21, 35]), np.array([72., 58.]))
test = np.genfromtxt(txt, dtype=None, unpack=True, encoding=None)
rossbar marked this conversation as resolved.
Show resolved Hide resolved
for arr, result in zip(expected, test):
assert_array_equal(arr, result)
assert_equal(arr.dtype, result.dtype)

def test_unpack_single_name(self):
# Regression test for gh-4341
# Unpacking should work when structured dtype has only one field
txt = TextIO("21\n35")
dt = {'names': ('a',), 'formats': ('<i4',)}
rossbar marked this conversation as resolved.
Show resolved Hide resolved
expected = np.array([21, 35], dtype=np.int32)
test = np.genfromtxt(txt, dtype=dt, unpack=True)
assert_array_equal(expected, test)
assert_equal(expected.dtype, test.dtype)

def test_squeeze_scalar(self):
# Regression test for gh-4341
# Unpacking a scalar should give zero-dim output,
# even if dtype is structured
txt = TextIO("1")
dt = {'names': ('a',), 'formats': ('<i4',)}
expected = np.array((1,), dtype=np.int32)
test = np.genfromtxt(txt, dtype=dt, unpack=True)
assert_array_equal(expected, test)
assert_equal((), test.shape)
assert_equal(expected.dtype, test.dtype)


class TestPathUsage:
# Test that pathlib.Path can be used
Expand Down