fumitoh / modelx

Use Python like a spreadsheet!
https://modelx.io
GNU Lesser General Public License v3.0
90 stars 20 forks source link

new_space_from_pandas doesn't allow non string space_params #22

Open alebaran opened 4 years ago

alebaran commented 4 years ago

New_space_from_pandas doesn't allow non string space_params:

import pandas as pd
import numpy as np
import modelx as mx

def make_sample2(columns, idx_names):
    """Series with MultiIndex"""

    arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
              ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]

    tuples = list(zip(*arrays))
    index = pd.MultiIndex.from_tuples(tuples, names=idx_names)

    return pd.DataFrame(np.random.randn(8, 2), index=index, columns=columns)

df=make_sample2(None, ["Col1", "Col2"])
space_params = [2]

m = mx.new_model()
m.new_space_from_pandas(
    df, cells=["Col1", "Col2"], param=None,
    space_params=space_params, cells_params=None)
fumitoh commented 4 years ago

Did you mean this?

import pandas as pd
import numpy as np
import modelx as mx

def make_sample2(columns, idx_names):
    """Series with MultiIndex"""

    arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
              ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]

    tuples = list(zip(*arrays))
    index = pd.MultiIndex.from_tuples(tuples, names=idx_names)

    return pd.DataFrame(np.random.randn(8, 2), index=index, columns=columns)

df=make_sample2(None, ["Col1", "Col2"])

m = mx.new_model()
m.new_space_from_pandas(
    df,
    cells=["Cells1", "Cells2"],   # must be different from the param names
    space_params=[1])  # 0-based indexing, i.e. the 2nd index == "Col2"

print(df)

#                   0         1
# Col1 Col2
# bar  one   0.616599 -0.181080
#      two   0.318790 -1.017757
# baz  one  -0.455583  1.215206
#      two   2.099919  0.430696
# foo  one  -2.672232 -0.144333
#      two  -1.948054  2.964407
# qux  one   1.156770 -0.326689
#      two   1.586994  0.746322

m.Space1.parameters # => ('Col2',)

print(m.Space1['one'].frame)

#         Cells1    Cells2
# Col1
# bar   0.616599 -0.181080
# baz  -0.455583  1.215206
# foo  -2.672232 -0.144333
# qux   1.156770 -0.326689

print(m.Space1['two'].frame)

#         Cells1    Cells2
# Col1
# bar   0.318790 -1.017757
# baz   2.099919  0.430696
# foo  -1.948054  2.964407
# qux   1.586994  0.746322
alebaran commented 4 years ago

Clear, I didn't understand the function parameters earlier.