MaxCompute supports user-defined functions (UDFs), PyODPS, and MaxFrame for job development. You can use images to include third-party Python packages such as pandas and SciPy in your UDF, PyODPS, and MaxFrame jobs.
Use images in SQL UDFs
The following example creates a pandas-based UDF that sums the values of two columns.
-
Write a Python UDF script and save it as a
sum_pandas.pyfile. The following code provides an example:from odps.udf import annotate import pandas as pd @annotate("string, string -> string") class SumColumns(object): def evaluate(self, arg1, arg2): # Convert the input arguments to a pandas DataFrame. df = pd.DataFrame({'col1': arg1.split(','), 'col2': arg2.split(',')}) # Process the data by using pandas. # This example calculates the sum of two columns. df['sum'] = df['col1'].astype(int) + df['col2'].astype(int) # Convert the result to a string and return it. result = ','.join(df['sum'].astype(str).values) return result -
Upload the
sum_pandas.pyscript as a resource to your MaxCompute project. For more information, see Add resources. The following sample command shows how to upload the script:ADD PY sum_pandas.py -f; -
Register the
sum_pandas.pyscript that you uploaded as the SumColumns user-defined function. For more information, see Register a function. The following sample command shows how to register the function:CREATE FUNCTION SumColumns AS 'sum_pandas.SumColumns' USING 'sum_pandas.py'; -
Create a test table named
testsumand insert test data into the table.CREATE TABLE testsum (col1 string, col2 string); INSERT INTO testsum VALUES ('1,2,3','1,2,3'),('1,2,3','3,2,1'),('1,2,3','4,5,6'); -
Call the UDF and specify an existing image by using a flag.
set odps.sql.python.version=cp37; set odps.session.image = <image_name>; SELECT SumColumns(col1,col2) AS result FROM testsum;The following result is returned:
+------------+ | result | +------------+ | 2,4,6 | | 4,4,4 | | 5,7,9 | +------------+
Use images in PyODPS
The following example uses an image to call the psi function from the SciPy package in a PyODPS job.
-
Create a test table named
test_float_coland insert test data into the table.CREATE TABLE test_float_col (col1 double); INSERT INTO test_float_col VALUES (3.75),(2.51); -
Write a PyODPS script to calculate the value of
psi(col1), save the script as apsi_col.pyfile, and then run the file. The following code provides an example:import os from odps import ODPS, options def my_psi(v): from scipy.special import psi return float(psi(v)) # If the project has isolation enabled, the following option is not required. options.sql.settings = {"odps.isolation.session.enable": True} o = ODPS( # Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set to your AccessKey ID, # and the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set to your AccessKey secret. # We recommend that you do not hardcode your AccessKey ID and AccessKey secret in the code. os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), project='your-default-project', endpoint='your-end-point' ) df = o.get_table("test_float_col").to_df() # Execute the job and retrieve the result. df.col1.map(my_psi).execute(image='scipy') # Save the result to another table. df.col1.map(my_psi).persist("result_table", image='scipy')Parameter description:
-
ALIBABA_CLOUD_ACCESS_KEY_ID: Set this environment variable to an AccessKey ID that has the required MaxCompute permissions on the objects in the target MaxCompute project. To obtain an AccessKey ID, go to the AccessKey Management page.
-
ALIBABA_CLOUD_ACCESS_KEY_SECRET: Set this environment variable to the AccessKey secret that corresponds to the AccessKey ID.
-
your-default-project: The name of your MaxCompute project. To view the project name, log on to the MaxCompute console and choose Workspace > Projects in the left-side navigation pane.
-
your-end-point: The endpoint of the region where your MaxCompute project resides. You can select an endpoint based on your network connection type, for example,
http://service.cn-chengdu.maxcompute.aliyun.com/api. For more information, see Endpoints.
-
-
View the results in the
result_tabletable.SELECT * FROM result_tableThe following result is returned:
+------------+ | col1 | +------------+ | 1.1825373886117962 | | 0.7080484451910534 | +------------+
Use images in MaxFrame
The following example uses an image to call the psi function from the SciPy package in a MaxFrame job.
-
Create a test table named
test_float_coland insert test data into the table.CREATE TABLE test_float_col (col1 double); INSERT INTO test_float_col VALUES (3.75),(2.51); -
Write a MaxFrame script to calculate the value of
psi(col1), save the script as apsi_col.pyfile, and then run the file. The following code provides an example:import os from odps import ODPS, options from maxframe.session import new_session import maxframe.dataframe as md from maxframe.config import options from maxframe import config # Reference the built-in SciPy image. config.options.sql.settings = { "odps.session.image": "scipy" } def my_psi(v): from scipy.special import psi return float(psi(v)) o = ODPS( # Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set to your AccessKey ID, # and the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set to your AccessKey secret. # We recommend that you do not hardcode your AccessKey ID and AccessKey secret in the code. os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), project='your-default-project', endpoint='your-end-point' ) # Create a MaxFrame session. session = new_session(o) df = md.read_odps_table('test_float_col') # Execute the job and retrieve the result. print(df.col1.map(my_psi).execute().fetch())Parameter description:
-
ALIBABA_CLOUD_ACCESS_KEY_ID: Set this environment variable to an AccessKey ID that has the required MaxCompute permissions on the objects in the target MaxCompute project. To obtain an AccessKey ID, go to the AccessKey Management page.
-
ALIBABA_CLOUD_ACCESS_KEY_SECRET: Set this environment variable to the AccessKey secret that corresponds to the AccessKey ID.
-
your-default-project: The name of your MaxCompute project. To view the project name, log on to the MaxCompute console and choose Workspace > Projects in the left-side navigation pane.
-
your-end-point: The endpoint of the region where your MaxCompute project resides. You can select an endpoint based on your network connection type, for example,
http://service.cn-chengdu.maxcompute.aliyun.com/api. For more information, see Endpoints.
The following result is returned:
0 1.182537 1 0.708048 Name: col1, dtype: float64 -