diff options
author | ahaldane <ealloc@gmail.com> | 2017-01-17 22:59:28 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-01-17 22:59:28 -0500 |
commit | 20d6ca1bd0c23cf22880ea72ae7abb4b67d41894 (patch) | |
tree | 9e5212a4df08956efd174ce6146983c3972fdb5e /numpy | |
parent | 8940a6533132ab11edbd0520ee0f0329c3a7f329 (diff) | |
parent | 3caf1223b9b8e4747fb7b41b2fbd2122ee175d03 (diff) | |
download | numpy-20d6ca1bd0c23cf22880ea72ae7abb4b67d41894.tar.gz |
Merge pull request #8486 from eric-wieser/patch-8
BUG: Prevent crash for length-0 input to fromrecords
Diffstat (limited to 'numpy')
-rw-r--r-- | numpy/core/records.py | 4 | ||||
-rw-r--r-- | numpy/core/tests/test_records.py | 26 |
2 files changed, 27 insertions, 3 deletions
diff --git a/numpy/core/records.py b/numpy/core/records.py index 09511c5e6..91b70614c 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -626,7 +626,6 @@ def fromarrays(arrayList, dtype=None, shape=None, formats=None, return _array -# shape must be 1-d if you use list of lists... def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a recarray from a list of records in text form @@ -657,10 +656,9 @@ def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, [(456, 'dbe', 1.2) (2, 'de', 1.3)] """ - nfields = len(recList[0]) if formats is None and dtype is None: # slower obj = sb.array(recList, dtype=object) - arrlist = [sb.array(obj[..., i].tolist()) for i in range(nfields)] + arrlist = [sb.array(obj[..., i].tolist()) for i in range(obj.shape[-1])] return fromarrays(arrlist, formats=formats, shape=shape, names=names, titles=titles, aligned=aligned, byteorder=byteorder) diff --git a/numpy/core/tests/test_records.py b/numpy/core/tests/test_records.py index bd1fc014e..74a3be533 100644 --- a/numpy/core/tests/test_records.py +++ b/numpy/core/tests/test_records.py @@ -28,6 +28,32 @@ class TestFromrecords(TestCase): assert_equal(r['col2'].dtype.itemsize, 3) assert_equal(r['col3'].dtype.kind, 'f') + def test_fromrecords_0len(self): + """ Verify fromrecords works with a 0-length input """ + dtype = [('a', np.float), ('b', np.float)] + r = np.rec.fromrecords([], dtype=dtype) + assert_equal(r.shape, (0,)) + + def test_fromrecords_2d(self): + data = [ + [(1, 2), (3, 4), (5, 6)], + [(6, 5), (4, 3), (2, 1)] + ] + expected_a = [[1, 3, 5], [6, 4, 2]] + expected_b = [[2, 4, 6], [5, 3, 1]] + + # try with dtype + r1 = np.rec.fromrecords(data, dtype=[('a', int), ('b', int)]) + assert_equal(r1['a'], expected_a) + assert_equal(r1['b'], expected_b) + + # try with names + r2 = np.rec.fromrecords(data, names=['a', 'b']) + assert_equal(r2['a'], expected_a) + assert_equal(r2['b'], expected_b) + + assert_equal(r1, r2) + def test_method_array(self): r = np.rec.array(asbytes('abcdefg') * 100, formats='i2,a3,i4', shape=3, byteorder='big') assert_equal(r[1].item(), (25444, asbytes('efg'), 1633837924)) |