Skip to content

df.from_records should accept values deriving from ABC collections.Mapping #3000 #3005

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
2 commits merged into from Mar 15, 2013
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
4 changes: 4 additions & 0 deletions doc/source/v0.11.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,10 @@ Enhancements
- value_counts() now accepts a "normalize" argument, for normalized
histograms. (GH2710_).

- DataFrame.from_records now accepts not only dicts but any instance of
the collections.Mapping ABC.



Bug Fixes
~~~~~~~~~
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import csv
import operator
import sys
import collections

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

if isinstance(data[0], (list, tuple, dict, Series)):
if isinstance(data[0], (list, tuple, collections.Mapping, Series)):
arrays, columns = _to_arrays(data, columns, dtype=dtype)
columns = _ensure_index(columns)

Expand Down Expand Up @@ -5527,7 +5528,7 @@ def _to_arrays(data, columns, coerce_float=False, dtype=None):
if isinstance(data[0], (list, tuple)):
return _list_to_arrays(data, columns, coerce_float=coerce_float,
dtype=dtype)
elif isinstance(data[0], dict):
elif isinstance(data[0], collections.Mapping):
return _list_of_dict_to_arrays(data, columns,
coerce_float=coerce_float,
dtype=dtype)
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3246,6 +3246,22 @@ def test_to_records_dt64(self):
rs = df.to_records(convert_datetime64=False)
self.assert_(rs['index'][0] == df.index.values[0])

def test_to_records_with_Mapping_type(self):
import email
from email.parser import Parser
import collections

collections.Mapping.register(email.message.Message)

headers = Parser().parsestr('From: <user@example.com>\n'
'To: <someone_else@example.com>\n'
'Subject: Test message\n'
'\n'
'Body would go here\n')

frame = DataFrame.from_records([headers])
all( x in frame for x in ['Type','Subject','From'])

def test_from_records_to_records(self):
# from numpy documentation
arr = np.zeros((2,), dtype=('i4,f4,a10'))
Expand Down