全部產品
Search
文件中心

MaxCompute:基於MaxFrame實現分布式Pandas處理

更新時間:Apr 22, 2026

MaxFrame可以在分布式環境下使用與Pandas相同的API來分析資料,通過MaxFrame,您能夠以高於開源Pandas數十倍的效能在MaxCompute上快速完成資料分析和計算工作。本文為您介紹如何通過MaxFrame使用常用的Pandas運算元。

前提條件

已安裝MaxFrame,詳情請參見準備工作。

資料準備

  1. 在安裝了MaxFrame的Python環境下運行如下指令碼,準備測試表和測試資料。

    from odps import ODPS
    from maxframe.session import new_session
    import maxframe.dataframe as md
    import pandas as pd
    import os
    
    o = ODPS(
        # 確保 ALIBABA_CLOUD_ACCESS_KEY_ID 環境變數設定為使用者 Access Key ID,
        # ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境變數設定為使用者 Access Key Secret,
        # 不建議直接使用AccessKey ID和 AccessKey Secret字串。
        os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
        project='your-default-project',
        endpoint='your-end-point',
    )
    
    data_sets = [{
        "table_name": "product",
        "table_schema" : "index bigint, product_id bigint, product_name string, current_price bigint",
        "source_type": "records",
        "records" : [
            [1, 100, 'Nokia', 1000],
            [2, 200, 'Apple', 5000],
            [3, 300, 'Samsung', 9000]
        ],
    },
    {
        "table_name" : "sales",
        "table_schema" : "index bigint, sale_id bigint, product_id bigint, user_id bigint, year bigint, quantity bigint, price bigint",
        "source_type": "records",
        "records" : [
            [1, 1, 100, 101, 2008, 10, 5000],
            [2, 2, 300, 101, 2009, 7, 4000],
            [3, 4, 100, 102, 2011, 9, 4000],
            [4, 5, 200, 102, 2013, 6, 6000],
            [5, 8, 300, 102, 2015, 10, 9000],
            [6, 9, 100, 102, 2015, 6, 2000]
        ],
        "lifecycle": 5
    }]
    
    def prepare_data(o: ODPS, data_sets, suffix="", drop_if_exists=False):
        for index, data in enumerate(data_sets):
            table_name = data.get("table_name")
            table_schema = data.get("table_schema")
            source_type = data.get("source_type")
            
            if not table_name or not table_schema or not source_type:
                raise ValueError(f"Dataset at index {index} is missing one or more required keys: 'table_name', 'table_schema', or 'source_type'.")
    
            lifecycle = data.get("lifecycle", 5)
            table_name += suffix
            
            print(f"Processing {table_name}...")
            if drop_if_exists:
                print(f"Deleting {table_name}...")
                o.delete_table(table_name, if_exists=True)
            
            o.create_table(name=table_name, table_schema=table_schema, lifecycle=lifecycle, if_not_exists=True)
    
            if source_type == "local_file":
                file_path = data.get("file")
                if not file_path:
                    raise ValueError(f"Dataset at index {index} with source_type 'local_file' is missing the 'file' key.")
                sep = data.get("sep", ",")
                pd_df = pd.read_csv(file_path, sep=sep)
                ODPSDataFrame(pd_df).persist(table_name, drop_table=True)
            elif source_type == 'records':
                records = data.get("records")
                if not records:
                    raise ValueError(f"Dataset at index {index} with source_type 'records' is missing the 'records' key.")
                with o.get_table(table_name).open_writer() as writer:
                    writer.write(records)
            else:
                raise ValueError(f"Unknown data set source_type: {source_type}")
            
            print(f"Processed {table_name} Done")
    
    prepare_data(o, data_sets, "_maxframe_demo", True)

    參數說明:

    • ALIBABA_CLOUD_ACCESS_KEY_ID:需將該環境變數設定為具備目標MaxCompute專案中待操作對象相關MaxCompute許可權的AccessKey ID。您可以進入AccessKey管理頁面擷取AccessKey ID。

    • ALIBABA_CLOUD_ACCESS_KEY_SECRET:需將該環境變數設定為AccessKey ID對應的AccessKey Secret。

    • your-default-project:使用的MaxCompute專案名稱。您可以登入MaxCompute控制台,在左側導覽列選擇工作区>專案管理,查看MaxCompute專案名稱。

    • your-end-point:目標MaxCompute專案所在地區的Endpoint,可根據網路連接方式自行選擇,例如http://service.cn-chengdu.maxcompute.aliyun.com/api。詳情請參見Endpoint。

  2. 查詢sales_maxframe_demo表和product_maxframe_demo表的資料,SQL命令如下。

    --查詢sales_maxframe_demo表
    SELECT * FROM sales_maxframe_demo;
    
    --返回
    +------------+------------+------------+------------+------------+------------+------------+
    | index      | sale_id    | product_id | user_id    | year       | quantity   | price      |
    +------------+------------+------------+------------+------------+------------+------------+
    | 1          | 1          | 100        | 101        | 2008       | 10         | 5000       |
    | 2          | 2          | 300        | 101        | 2009       | 7          | 4000       |
    | 3          | 4          | 100        | 102        | 2011       | 9          | 4000       |
    | 4          | 5          | 200        | 102        | 2013       | 6          | 6000       |
    | 5          | 8          | 300        | 102        | 2015       | 10         | 9000       |
    | 6          | 9          | 100        | 102        | 2015       | 6          | 2000       |
    +------------+------------+------------+------------+------------+------------+------------+
    
    
    --查詢product_maxframe_demo表資料
    SELECT * FROM product_maxframe_demo;
    
    --返回
    +------------+------------+--------------+---------------+
    | index      | product_id | product_name | current_price |
    +------------+------------+--------------+---------------+
    | 1          | 100        | Nokia        | 1000          |
    | 2          | 200        | Apple        | 5000          |
    | 3          | 300        | Samsung      | 9000          |
    +------------+------------+--------------+---------------+

使用MaxFrame進行資料分析

  • 情境1:使用merge方法串連兩張資料表,以擷取sales_maxframe_demo表中所有sale_id對應的product_name以及該產品的所有year和price

    • 範例程式碼

      from odps import ODPS
      from maxframe.session import new_session
      import maxframe.dataframe as md
      import os
      
      o = ODPS(
          # 確保 ALIBABA_CLOUD_ACCESS_KEY_ID 環境變數設定為使用者 Access Key ID,
          # ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境變數設定為使用者 Access Key Secret,
          # 不建議直接使用 Access Key ID / Access Key Secret 字串
          os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
          os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
          project='your-default-project',
          endpoint='your-end-point',
      )
      
      session = new_session(o)
      
      #session id是一串用於關聯MaxFrame task的字元,對於調試和追蹤任務狀態有重要的作用。
      print(session.session_id)
      
      sales = md.read_odps_table("sales_maxframe_demo", index_col="index")
      product = md.read_odps_table("product_maxframe_demo", index_col="product_id")
      
      #這裡的df並不會立即執行,除非您使用df.execute()來觸發。
      #這意味著所有的計算都將最終完全在MaxCompute叢集完成,避免了中間所不必要的資料轉送和阻塞。
      df = sales.merge(product, left_on="product_id", right_index=True)
      df = df[["product_name", "year", "price"]]
      
      print(df.execute().fetch())
      
      #儲存結果到MaxCompute表中,並銷毀Session
      md.to_odps_table(df, "result_df", overwrite=True).execute()
      
      session.destroy()

      返回結果:

      index product_name  year  price                   
      1            Nokia  2008   5000
      2          Samsung  2009   4000
      3            Nokia  2011   4000
      4            Apple  2013   6000
      5          Samsung  2015   9000
      6            Nokia  2015   2000
    • 效能對比

      在sales表資料量為5000W條(size:1.96 GB),product表資料量為10W條(size:3 MB)的資料樣本中進行運算,可以得到如下耗時對比結果:

      環境

      耗時(單位:秒)

      本地Pandas(版本為1.3.5)

      65.8

      MaxFrame

      22

  • 情境2:選出每個出售過的產品第一年銷售的產品ID、年份、數量和價格

    • 範例程式碼

      from odps import ODPS
      from maxframe.session import new_session
      import maxframe.dataframe as md
      import os
      
      o = ODPS(
          # 確保 ALIBABA_CLOUD_ACCESS_KEY_ID 環境變數設定為使用者 Access Key ID,
          # ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境變數設定為使用者 Access Key Secret,
          # 不建議直接使用 Access Key ID / Access Key Secret 字串
          os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
          os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
          project='your-default-project',
          endpoint='your-end-point',
      )
      
      session = new_session(o)
      
      #session id是一串用於關聯MaxFrame task的字元,對於調試和追蹤任務狀態有重要的作用。
      print(session.session_id)
      
      # 彙總擷取每個產品的第一個年份
      min_year_df = md.read_odps_table("sales_maxframe_demo", index_col="index")
      min_year_df = min_year_df.groupby('product_id', as_index=False).agg(first_year=('year', 'min'))
      
      # join 找到對應的銷售記錄
      sales = md.read_odps_table("sales_maxframe_demo", index_col=['product_id', 'year'])
      result_df = md.merge(sales, min_year_df, 
                              left_index=True, 
                              right_on=['product_id','first_year'],
                              how='inner')
      
      #這裡的result_df並不會立即執行,除非您使用 result_df.execute()來觸發。
      #這意味著所有的計算都將最終完全在MaxCompute中叢集完成,避免了中間所不必要的資料轉送和阻塞。
      result_df = result_df[['product_id', 'first_year', 'quantity', 'price']]
      
      print(result_df.execute().fetch())
      
      #銷毀 Session
      session.destroy()

      返回結果:

          product_id  first_year  quantity  price
      100         100        2008        10   5000
      300         300        2009         7   4000
      200         200        2013         6   6000
    • 效能對比

      在sales表資料量為5000W條(size:1.96 GB),product表資料量為10W條(size:3 MB)的資料樣本中進行運算,可以得到如下耗時對比結果:

      環境

      耗時(單位:秒)

      本地Pandas(版本為1.3.5)

      186

      MaxFrame

      21

  • 情境3:為每個使用者擷取其消費最多的產品ID

    說明

    該情境將示範多次groupby、join、drop_duplicates和sort_values操作。

    • 範例程式碼

      from odps import ODPS
      from maxframe.session import new_session
      import maxframe.dataframe as md
      import os
      
      o = ODPS(
          os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
          os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
          project='your-default-project',
          endpoint='your-end-point',
      )
      
      session = new_session(o)
      
      #session id 是一串用於關聯 MaxFrame task 的字元,對於調試和追蹤任務狀態有重要的作用。
      print(session.session_id)
      
      sales = md.read_odps_table("sales_maxframe_demo", index_col="index")
      product = md.read_odps_table("product_maxframe_demo", index_col="product_id")
      
      sales['total'] = sales['price'] * sales['quantity']
      
      product_cost_df = sales.groupby(['product_id', 'user_id'], as_index=False).agg(user_product_total=('total','sum'))
      product_cost_df = product_cost_df.merge(product, left_on="product_id", right_index=True, how='right')
      
      user_cost_df = product_cost_df.groupby('user_id').agg(max_total=('user_product_total', 'max'))
      merge_df = product_cost_df.merge(user_cost_df, left_on='user_id', right_index=True)
      
      #這裡的 result_df 並不會立即執行,除非您使用 result_df.execute()來觸發。
      #這意味著所有的計算都將最終完全在 MaxCompute 中叢集完成,避免了中間所不必要的資料轉送和阻塞。
      result_df = merge_df[merge_df['user_product_total'] == merge_df['max_total']][['user_id', 'product_id']].drop_duplicates().sort_values(['user_id'], ascending = [1])
      
      print(result_df.execute().fetch())
      
      #銷毀 Session
      
      session.destroy()

      返回結果:

           user_id  product_id
      100      101         100
      300      102         300
    • 效能對比

      在sales表資料量為5000W條(size:1.96 GB),product表資料量為10W條(size:3 MB)的資料樣本中進行計算,可以得到如下耗時對比結果:

      環境

      耗時(單位:秒)

      本地Pandas(版本為1.3.5)

      176

      MaxFrame

      85

結論

MaxFrame相容Pandas介面且自動進行分散式處理,在保證強巨量資料處理能力的同時,可以大幅度提高資料處理規模及計算效率。