Skip to content

Commit

Permalink
Make merge_tables api more flexible
Browse files Browse the repository at this point in the history
Allow the target argument to be either a string or wrapped table
and allow the tables sequence to have table names (strings) or
wrapped table instances.
  • Loading branch information
jiffyclub committed Aug 8, 2014
1 parent 163482e commit 430d934
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
15 changes: 12 additions & 3 deletions urbansim/sim/simulation.py
Expand Up @@ -1148,9 +1148,9 @@ def merge_tables(target, tables, columns=None):
Parameters
----------
target : str
Name of the table onto which tables will be merged.
tables : list of `DataFrameWrapper` or `TableFuncWrapper`
target : str, DataFrameWrapper, or TableFuncWrapper
Name of the table (or wrapped table) onto which tables will be merged.
tables : list of `DataFrameWrapper`, `TableFuncWrapper`, or str
All of the tables to merge. Should include the target table.
columns : list of str, optional
If given, columns will be mapped to `tables` and only those columns
Expand All @@ -1163,6 +1163,15 @@ def merge_tables(target, tables, columns=None):
merged : pandas.DataFrame
"""
# allow target to be string or table wrapper
if isinstance(target, (DataFrameWrapper, TableFuncWrapper)):
target = target.name

# allow tables to be strings or table wrappers
tables = [get_table(t)
if not isinstance(t, (DataFrameWrapper, TableFuncWrapper)) else t
for t in tables]

merges = {t.name: {} for t in tables}
tables = {t.name: t for t in tables}
casts = _get_broadcasts(tables.keys())
Expand Down
9 changes: 2 additions & 7 deletions urbansim/sim/tests/test_mergetables.py
Expand Up @@ -123,7 +123,7 @@ def test_merge_tables1(dfa, dfz, dfb):
def test_merge_tables2(dfa, dfz, dfb, dfc):
all_broadcasts()

merged = sim.merge_tables('c', [dfa, dfz, dfb, dfc])
merged = sim.merge_tables(dfc, [dfa, dfz, dfb, dfc])

expected = pd.merge(
dfa.to_frame(), dfb.to_frame(), left_index=True, right_on='a_id')
Expand Down Expand Up @@ -177,12 +177,7 @@ def test_merge_tables3():
sim.broadcast(cast='b', onto='d', cast_index=True, onto_on='b_id')
sim.broadcast(cast='c', onto='d', cast_index=True, onto_on='c_id')

a = sim.get_table('a')
b = sim.get_table('b')
c = sim.get_table('c')
d = sim.get_table('d')

df = sim.merge_tables(target='d', tables=[a, b, c, d])
df = sim.merge_tables(target='d', tables=['a', 'b', 'c', 'd'])

expected = pd.merge(df_a, df_b, left_index=True, right_on='a_id')
expected = pd.merge(expected, df_d, left_index=True, right_on='b_id')
Expand Down

0 comments on commit 430d934

Please sign in to comment.