summaryrefslogtreecommitdiff
path: root/numpy
diff options
context:
space:
mode:
authordojafrat <65087820+dojafrat@users.noreply.github.com>2020-05-13 15:38:50 -0500
committerGitHub <noreply@github.com>2020-05-13 15:38:50 -0500
commit1459b9802fcc37e1eab1b1e139b8db74ba69831f (patch)
tree8d6f0bfd39eb9c03ab32aa91377e5a2daa8c49d7 /numpy
parent5f7114ca823736e3f55176cf6a3fbeb77efe0279 (diff)
downloadnumpy-1459b9802fcc37e1eab1b1e139b8db74ba69831f.tar.gz
DOC: Improve docstring of ``numpy.core.records`` (#16199)
Add documentation and examples to fromstring function See #15853 Co-authored-by: Eric Wieser <wieser.eric@gmail.com>
Diffstat (limited to 'numpy')
-rw-r--r--numpy/core/records.py54
1 files changed, 52 insertions, 2 deletions
diff --git a/numpy/core/records.py b/numpy/core/records.py
index 04c970cf4..af59de425 100644
--- a/numpy/core/records.py
+++ b/numpy/core/records.py
@@ -772,8 +772,58 @@ def fromrecords(recList, dtype=None, shape=None, formats=None, names=None,
def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None,
names=None, titles=None, aligned=False, byteorder=None):
- """Create a (read-only) record array from binary data contained in
- a string"""
+ """Create a record array from binary data
+
+ Note that despite the name of this function it does not accept `str`
+ instances.
+
+ Parameters
+ ----------
+ datastring : bytes-like
+ Buffer of binary data
+ dtype : data-type, optional
+ Valid dtype for all arrays
+ shape : int or tuple of ints, optional
+ Shape of each array.
+ offset : int, optional
+ Position in the buffer to start reading from.
+ formats, names, titles, aligned, byteorder :
+ If `dtype` is ``None``, these arguments are passed to
+ `numpy.format_parser` to construct a dtype. See that function for
+ detailed documentation.
+
+
+ Returns
+ -------
+ np.recarray
+ Record array view into the data in datastring. This will be readonly
+ if `datastring` is readonly.
+
+ See Also
+ --------
+ numpy.frombuffer
+
+ Examples
+ --------
+ >>> a = b'\x01\x02\x03abc'
+ >>> np.core.records.fromstring(a, dtype='u1,u1,u1,S3')
+ rec.array([(1, 2, 3, b'abc')],
+ dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1'), ('f3', 'S3')])
+
+ >>> grades_dtype = [('Name', (np.str_, 10)), ('Marks', np.float64),
+ ... ('GradeLevel', np.int32)]
+ >>> grades_array = np.array([('Sam', 33.3, 3), ('Mike', 44.4, 5),
+ ... ('Aadi', 66.6, 6)], dtype=grades_dtype)
+ >>> np.core.records.fromstring(grades_array.tobytes(), dtype=grades_dtype)
+ rec.array([('Sam', 33.3, 3), ('Mike', 44.4, 5), ('Aadi', 66.6, 6)],
+ dtype=[('Name', '<U10'), ('Marks', '<f8'), ('GradeLevel', '<i4')])
+
+ >>> s = '\x01\x02\x03abc'
+ >>> np.core.records.fromstring(s, dtype='u1,u1,u1,S3')
+ Traceback (most recent call last)
+ ...
+ TypeError: a bytes-like object is required, not 'str'
+ """
if dtype is None and formats is None:
raise TypeError("fromstring() needs a 'dtype' or 'formats' argument")