Skip to content

Commit 15847d6

Browse files
author
y-p
committed
Merge pull request #3005 from y-p/GH3000
df.from_records should accept values deriving from ABC collections.Mapping #3000
2 parents b513215 + a4ca1db commit 15847d6

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

doc/source/v0.11.0.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,10 @@ Enhancements
280280
- value_counts() now accepts a "normalize" argument, for normalized
281281
histograms. (GH2710_).
282282

283+
- DataFrame.from_records now accepts not only dicts but any instance of
284+
the collections.Mapping ABC.
285+
286+
283287

284288
Bug Fixes
285289
~~~~~~~~~

pandas/core/frame.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import csv
1818
import operator
1919
import sys
20+
import collections
2021

2122
from numpy import nan as NA
2223
import numpy as np
@@ -413,7 +414,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
413414
if index is None and isinstance(data[0], Series):
414415
index = _get_names_from_index(data)
415416

416-
if isinstance(data[0], (list, tuple, dict, Series)):
417+
if isinstance(data[0], (list, tuple, collections.Mapping, Series)):
417418
arrays, columns = _to_arrays(data, columns, dtype=dtype)
418419
columns = _ensure_index(columns)
419420

@@ -5528,7 +5529,7 @@ def _to_arrays(data, columns, coerce_float=False, dtype=None):
55285529
if isinstance(data[0], (list, tuple)):
55295530
return _list_to_arrays(data, columns, coerce_float=coerce_float,
55305531
dtype=dtype)
5531-
elif isinstance(data[0], dict):
5532+
elif isinstance(data[0], collections.Mapping):
55325533
return _list_of_dict_to_arrays(data, columns,
55335534
coerce_float=coerce_float,
55345535
dtype=dtype)

pandas/tests/test_frame.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3246,6 +3246,22 @@ def test_to_records_dt64(self):
32463246
rs = df.to_records(convert_datetime64=False)
32473247
self.assert_(rs['index'][0] == df.index.values[0])
32483248

3249+
def test_to_records_with_Mapping_type(self):
3250+
import email
3251+
from email.parser import Parser
3252+
import collections
3253+
3254+
collections.Mapping.register(email.message.Message)
3255+
3256+
headers = Parser().parsestr('From: <user@example.com>\n'
3257+
'To: <someone_else@example.com>\n'
3258+
'Subject: Test message\n'
3259+
'\n'
3260+
'Body would go here\n')
3261+
3262+
frame = DataFrame.from_records([headers])
3263+
all( x in frame for x in ['Type','Subject','From'])
3264+
32493265
def test_from_records_to_records(self):
32503266
# from numpy documentation
32513267
arr = np.zeros((2,), dtype=('i4,f4,a10'))

0 commit comments

Comments
 (0)