Initializing help system before first use

pygetdf

pygetdf


Purpose
Initialize a list of Mosel arrays from the columns of a pandas DataFrame.
Synopsis
procedure pygetdf(expr:string,result:list of array)
procedure pygetdf(expr:string,result:list of array,labels:list of string)
Arguments
expr 
Python expression that evaluates to a pandas DataFrame
result 
Mosel list of arrays to be initialized from pandas DataFrame
labels 
Labels of the pandas DataFrame columns used for initialization
Example
In this example, two Mosel arrays with the same index sets are initialized from a DataFrame. With the first call to pygetdf, the arrays are initialized based on the order of the DataFrame columns, with the second they are initialized using column labels.
declarations
    I, J: set of integer
    Numbers: dynamic array(I, J) of integer
    Labels: dynamic array(I, J) of string
end-declarations

pyinitpandas
pyexec(`
import pandas as pd
df = pd.DataFrame(
    data=[[11, "eleven"], [23, "twenty-three"], [42, "forty-two"]],
    index=pd.MultiIndex.from_tuples([(1, 1), (2, 3), (4, 2)]),
    columns=["number", "label"])
print(df)
`)

pygetdf("df", [Numbers, Labels])
writeln("I: ", I, "\nJ: ", J)
writeln("Numbers: ", Numbers, "\nLabels:  ", Labels)

reset(Numbers); reset(Labels)
pygetdf("df", [Labels, Numbers], ["label", "number"])
writeln("Numbers: ", Numbers, "\nLabels:  ", Labels)
Further information
1. The first version of the procedure initializes the arrays based on the order of the DataFrame columns. The second version uses column labels to select the DataFrame columns that are used for the initialization.
2. At first, the procedure interprets the expression as a global variable name and tries to access the variable by getting it from the attributes of the Python __main__ module. If this fails, the expression is evaluated by Python and the result is used for the Mosel array initialization. It is a fatal error if the expression evaluation or the type conversion fails.
3. The initialization of the result arrays is additive: new elements are written to the existing arrays without clearing previously existing elements. Use reset to manually clear the arrays before calling this procedure.
4. DataFrame conversion is supported in all module functions that accept lists of arrays. In particular, it is supported by pycall and the I/O Driver python .
5. Do not concatenate untrusted strings from the end user into the expr string. See Section Xpress Insight configuration for more information.
Related topics
Module
python3