How to Call Python From Mathematica, Including NumPy
A tutorial on how to use two popular and powerful languages for data manipulation and data science together.
Join the DZone community and get the full member experience.
Join For FreeThe Mathematica function ExternalEvalute
lets you call Python from Mathematica. However, there are a few wrinkles.
I first pasted in an example from the Mathematica documentation and it failed.
ExternalEvaluate[
"Python",
{"def f(x): return x**2", "f(3)"}
]
It turns out you (may) have to tell Mathematica where to find Python. I ran the following, tried again, and the example worked.
RegisterExternalEvaluator[
"Python",
"C:\\bin\\Anaconda3\\python.EXE"
]
You can also run Python with NumPy loaded using
ExternalEvaluate["Python-NumPy", ... ]
except that didn't work the first time either. You have to register a Python-NumPy
evaluator separately. So I ran
RegisterExternalEvaluator[
"Python-NumPy",
"C:\\bin\\Anaconda3\\python.EXE"
]
and then tried again calling Python code using NumPy. But then there's the question of how it imports NumPy. Does it simply run import numpy
, or maybe from numpy import *
, or maybe import numpy as np
? It turns out the first possibility is what happens. So to print pi
from NumPy, your code string needs to be numpy.pi
.
You don't need to use Python-NumPy
if you just do your own importing. For example, this code returns π².
ExternalEvaluate[
"Python",
"import numpy; x = numpy.pi; x**2"
]
And you can import any library you'd like, not just NumPy.
ExternalEvaluate[
"Python",
"from sympy import isprime; isprime(7)"
]
Everything above applies to Mathematica 11.3 and Mathematica 12.
Published at DZone with permission of John Cook, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments