Differences between revisions 6 and 7
Revision 6 as of 2022-09-24 20:20:46
Size: 2480
Comment:
Revision 7 as of 2022-09-24 20:20:50
Size: 2442
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
## page was renamed from StataPython

Stata Python


Installation

The path to the Python executable is set using:

python set exec "path_string"

Stata can list recognized Python environments with python search.

To prepend or append to the PYTHONPATH, use:

python set userpath "path_string" [...], [prepend]

To make these settings permanent, use the permanent option.


Usage

Python REPL

A Python REPL is entered with the python command. It prints to the screen a reminder that the end command is used to exit the environment.

Stata local variables are accessed with quotations.

. local int_var = 3
. local str_var = "This is a Stata string"
. python
---------------------------------------- python (type end to exit) -----------
>>> `int_var'
3
>>> "`str_var'".split(" ")
['This', 'is', 'a', 'Stata', 'string']

Within the REPL, the stata context submits commands to the parent Stata shell.

>>> stata: sysuse auto, clear

Python Scope

A Python scope can be entered with python: (similar to defining function in Stata). This Python environment is exited upon leaving the scope, i.e. the end of the statement. To submit multiple statements, delimit them with semicolons.

Python SFI Module

A foreign function interface module is also available.

from sfi import Data
pymake = Data.get('make')
# do something

This can even be used within the Python REPL that is running within the Stata shell.

Stata Do Files

Python scopes within a Do file are entered with python: and terminated with end.

sysuse auto, clear
python:
from sfi import Data
pymake = Data.get(’make’)
# do something
end

A common strategy is to define Python functions within a Do file, then create Stata functions to interface.

program varsum
    version 16.0
    syntax varname [if] [in]

    python: _varsum("`varlist'", "`touse'")
    display as txt " sum of ‘varlist’: " as res r(sum)
end

python:
from sfi import Data, Scalar
def _varsum(varname, touse):
    x = Data.get(varname, None, touse)
    Scalar.setValue("r(sum)", sum(x))
end

. sysuse auto, clear
(1978 Automobile Data)

. varsum price
sum of price: 456229

. varsum price if foreign
sum of price: 140463


CategoryRicottone

Stata/Python (last edited 2023-09-26 18:26:25 by DominicRicottone)