Skip to content

PERF: nested dict DataFrame construction #11158

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
merged 1 commit into from
Sep 21, 2015
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.17.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1032,6 +1032,7 @@ Performance Improvements
- Improved performance of ``to_datetime`` when specified format string is ISO8601 (:issue:`10178`)
- 2x improvement of ``Series.value_counts`` for float dtype (:issue:`10821`)
- Enable ``infer_datetime_format`` in ``to_datetime`` when date components do not have 0 padding (:issue:`11142`)
- Regression from 0.16.1 in constructing ``DataFrame`` from nested dictionary (:issue:`11084`)
Copy link
Contributor

Choose a reason for hiding this comment

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

add with dateimelikes?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Actually, this affected any type


.. _whatsnew_0170.bug_fixes:

Expand Down
11 changes: 9 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@

from pandas.tseries.period import PeriodIndex
from pandas.tseries.index import DatetimeIndex
from pandas.tseries.tdi import TimedeltaIndex


import pandas.core.algorithms as algos
import pandas.core.base as base
Expand Down Expand Up @@ -5400,8 +5402,13 @@ def _homogenize(data, index, dtype=None):
v = v.reindex(index, copy=False)
else:
if isinstance(v, dict):
v = _dict_compat(v)
oindex = index.astype('O')
if oindex is None:
oindex = index.astype('O')

if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't remember why we do this, but is PeriodIndex needed as well? (and do we have tests for same)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is to handle the case where the dict had datetime/timedelta64s as the keys - they're boxed in creating the index, so need to be changed in the dict too so the lookups work. From this PR #10269.

AFAIK not needed for PeriodIndex since there aren't any types that get coerced to it? This test covers nested construction with a PeriodIndex.
https://github.com/pydata/pandas/blob/master/pandas/tseries/tests/test_period.py#L2078

Copy link
Contributor

Choose a reason for hiding this comment

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

ok, can you move all of these types of tests to the same location (e.g. out of test_period, not sure where datetimeindex/timedeltaindex are) and prob into test_frame (though I hate adding to this, its really IS part of it).

v = _dict_compat(v)
else:
v = dict(v)
v = lib.fast_multiget(v, oindex.values, default=NA)
v = _sanitize_array(v, index, dtype=dtype, copy=False,
raise_cast_failure=False)
Expand Down
23 changes: 22 additions & 1 deletion pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from pandas import (DataFrame, Index, Series, Panel, notnull, isnull,
MultiIndex, DatetimeIndex, Timestamp, date_range,
read_csv, timedelta_range, Timedelta, CategoricalIndex,
option_context)
option_context, period_range)
from pandas.core.dtypes import DatetimeTZDtype
import pandas as pd
from pandas.parser import CParserError
Expand Down Expand Up @@ -3061,6 +3061,27 @@ def create_data(constructor):
assert_frame_equal(result_timedelta, expected)
assert_frame_equal(result_Timedelta, expected)

def test_nested_dict_frame_constructor(self):
rng = period_range('1/1/2000', periods=5)
df = DataFrame(randn(10, 5), columns=rng)

data = {}
for col in df.columns:
for row in df.index:
data.setdefault(col, {})[row] = df.get_value(row, col)

result = DataFrame(data, columns=rng)
tm.assert_frame_equal(result, df)

data = {}
for col in df.columns:
for row in df.index:
data.setdefault(row, {})[col] = df.get_value(row, col)

result = DataFrame(data, index=rng).T
tm.assert_frame_equal(result, df)


def _check_basic_constructor(self, empty):
"mat: 2d matrix with shpae (3, 2) to input. empty - makes sized objects"
mat = empty((2, 3), dtype=float)
Expand Down
20 changes: 0 additions & 20 deletions pandas/tseries/tests/test_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -2075,26 +2075,6 @@ def test_period_set_index_reindex(self):
df = df.set_index(idx2)
self.assertTrue(df.index.equals(idx2))

def test_nested_dict_frame_constructor(self):
rng = period_range('1/1/2000', periods=5)
df = DataFrame(randn(10, 5), columns=rng)

data = {}
for col in df.columns:
for row in df.index:
data.setdefault(col, {})[row] = df.get_value(row, col)

result = DataFrame(data, columns=rng)
tm.assert_frame_equal(result, df)

data = {}
for col in df.columns:
for row in df.index:
data.setdefault(row, {})[col] = df.get_value(row, col)

result = DataFrame(data, index=rng).T
tm.assert_frame_equal(result, df)

def test_frame_to_time_stamp(self):
K = 5
index = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
Expand Down