2.17.1 Example of Python Object

Minimum Origin Version Required: Origin 2017 SR1

We will show how to perform a Logistic regression by using LabTalk Python object in the following example.

Note: In this example, we will use Python extensions in it. In order to make the example easier to understand, it is strongly recommended to read the note about how to use Python extensions at first.

Python Object

We first read the data into Origin worksheet, and send the data as a Python list object. Then perform Logistic Regression in Python, finally send the Python’s fitted coefficients in a list object to Origin’s worksheet.

//Python object example to call Python in LabTalk

//Check whether Python is installed
if( Python.Init()<0 )
	type -b "Initialize failed.";
//Add the installation folder of Python extension to system path list
Python.Exec("import sys");
//Optionally, modify the path of installation folder 
Python.Exec("PkPath = "C:\Python33\Lib\site-packages"");

//Import sample data
string fn = system.path.program$ + "Samples\Statistics\LogRegData.dat"; 
impasc fname:=fn$ options.sparklines:=0;

//Send data in worksheet to Python
for (ii = 1; ii <= wks.ncols; ii++)
	range rr = 1!$(ii);
	Python.Send(rr, var$(ii));

//Run logistic regression in Python
//Results are stored in Python's list object result
Python.Exec("import pandas as pd");
Python.Exec("import numpy as np");
Python.Exec("import statsmodels.api as sm");
Python.Exec("df = pd.DataFrame.from_items([('Age', var1), ('Salary', var2),('Gender',var3),('Career_Change',var4)])");
Python.Exec("df['Gender'] = df['Gender'].astype('category')");
Python.Exec("df['Career_Change'] = df['Career_Change'].astype('category')");
Python.Exec("cat_columns = df.select_dtypes(['category']).columns");
Python.Exec("df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)");
Python.Exec("df['intercept'] = 1.0");
Python.Exec("logit = sm.Logit(df['Career_Change'], df[['Age','Salary','Gender','intercept']])");
Python.Exec("result = logit.fit()");

//New a workbook to output Python's result
page.longname$ = "Logistic Regression Result";

//Send Python's fitted coefficients in list object to Origin's worksheet 
//Send Python's fitted coefficients in list object to Origin's worksheet 
Python.Receive("1", list(result.params.index));
wks.col2.lname$ = Fitted parameter;
Python.Receive("2", list(result.params));
wks.col3.lname$ = 95% CI lower;
Python.Receive("3", list(result.conf_int()[1]));
wks.col4.lname$ = 95% CI upper;
Python.Receive("4", list(result.conf_int()[1]));

For your information, you can also learn how to perform Logistic regression in R by using LabTalk on this page if you are interested in.