すべてのプロダクト
Search
ドキュメントセンター

MaxCompute:DataFrameオブジェクトの作成

最終更新日:Jan 24, 2025

DataFrameは、構造化データの処理に使用されるAPIです。 PyODPSが提供するDataFrame APIを使用してデータ処理を実行できます。 これにより、開発効率が向上する。 このトピックでは、データソースを参照してDataFrameオブジェクトを作成する方法について説明します。

前提条件

サンプルテーブルpyodps_irisが利用可能です。 サンプルテーブルの作成方法の詳細については、「DataFrameを使用したデータ処理」をご参照ください。

背景情報

DataFrameオブジェクトを使用するには、Collection (DataFrame) 、Sequence、およびScalarオブジェクトの操作を理解しておく必要があります。 コレクションは、表形式のデータ構造 (2次元構造) を示す。 シーケンスはカラム (1次元構造) を示す。 スカラーはスカラーオブジェクトを示します。

Pandasを使用してDataFrameオブジェクトを作成すると、オブジェクトには実際のデータが含まれます。 MaxComputeテーブルを使用してDataFrameオブジェクトを作成する場合、オブジェクトには実際のデータは含まれません。 オブジェクトは、データ操作のみを含む。 DataFrameオブジェクトが作成されると、MaxComputeはデータを保存および計算できます。

手順

DataFrameオブジェクトは、作成する必要がある唯一のコレクションオブジェクトです。 DataFrameオブジェクトは、MaxComputeテーブル、MaxComputeパーティション、Pandas DataFrameオブジェクト、およびSQLAlchemyテーブル (データベーステーブル) を参照するために使用できます。 これらのデータソースの参照操作は同じです。 コードを変更することなくデータを処理できます。 入力と出力のポインタを変更するだけです。 これにより、ローカルで実行されている少量のテストコードをMaxComputeに移行できます。 移行の精度は、PyODPS DataFrameによって保証されます。

MaxComputeテーブルからのDataFrameオブジェクトの作成

MaxComputeテーブルからDataFrameオブジェクトを作成する場合は、DataFrameメソッドでテーブルオブジェクトを指定するか、テーブルのto_dfメソッドを使用します。 サンプルコード:

from odps.df import DataFrame

# Specify a table object. 
iris = DataFrame(o.get_table('pyodps_iris'))
# Use the to_df method of the MaxCompute table. 
iris2 = o.get_table('pyodps_iris').to_df() 

MaxComputeテーブルのパーティションを使用してDataFrameオブジェクトを作成する

MaxComputeテーブルのパーティションを使用してDataFrameオブジェクトを作成する場合は、DataFrameメソッドでパーティションを指定するか、パーティションのto_dfメソッドを使用します。 サンプルコード:

from odps.df import DataFrame

# (Optional) Create a partitioned table named partitioned_table. If a partitioned table exists, you can replace the existing partitioned table with the partitioned table partitioned_table based on your business requirements. 
o.create_table('partitioned_table', ('num bigint, num2 double', 'pt string'), if_not_exists=True)
# Specify a table object. 
pt_df = DataFrame(o.get_table('partitioned_table').get_partition('pt=20171111'))
# Use the to_df method of the partition. 
pt_df2 = o.get_table('partitioned_table').get_partition('pt=20171111').to_df();

Pandas DataFrameオブジェクトを使用したDataFrameオブジェクトの作成

Pandas DataFrameオブジェクトを使用してDataFrameオブジェクトを作成する場合は、DataFrameメソッドでPandas DataFrameオブジェクトを指定します。

  • サンプルコード

    from odps.df import DataFrame
    
    # Create a DataFrame object by using a Pandas DataFrame object. 
    import pandas as pd
    import numpy as np
    df = DataFrame(pd.DataFrame(np.arange(9).reshape(3, 3), columns=list('abc')))
  • 使用上の注意

    Pandas DataFrameオブジェクトを使用してDataFrameオブジェクトを作成する場合は、DataFrameオブジェクトの初期化時に次の項目に注意してください。

    • PyODPS DataFrameは、NUMPY OBJECTまたはSTRINGデータ型を推論しようとします。 列が空の場合、エラーが返されます。 これらのエラーを防ぐには、unknown_as_stringTrueに設定し、この列のデータ型をSTRINGに変換します。

    • as_typeパラメーターを使用して、データ型を強制的に変換できます。 基本データ型を使用する場合、PyODPS DataFrameオブジェクトを作成するときにこの型が強制的に変換されます。 Pandas DataFrameオブジェクトにLISTまたはDICT列が含まれている場合、システムはこの列のデータ型を推測しません。 手動で _typeとして設定する必要があります。 as_typeパラメーターはDICTに設定する必要があります。

    • 例1: null_col2列のデータ型をfloatに設定します。

      df2 = DataFrame(df, unknown_as_string=True, as_type={'null_col2': 'float'})
      print(df2.dtypes)

      次の応答が返されます。

      odps.Schema {
        sepallength           float64
        sepalwidth            float64
        petallength           float64
        petalwidth            float64
        name                  string
        null_col1             string   # The data type cannot be identified. You can set unknown_as_string to True to convert the data type into STRING. 
        null_col2             float64  # The data type is forcefully converted into FLOAT. 
      }
    • 例2: list_col列のデータ型をlist<int64> に設定します。

      df4 = DataFrame(df3, as_type={'list_col': 'list<int64>'})
      print(df4.dtypes)

      次の応答が返されます。

      odps.Schema {
        id        int64
        list_col  list<int64>  # The data type cannot be identified or automatically converted. You must specify as_type. 
      }
    説明

    PyODPSでは、Object Storage Service (OSS) またはTablestore外部テーブルをMaxComputeにアップロードすることはできません。

SQLAlchemyテーブルを使用したDataFrameオブジェクトの作成

SQLAlchemyテーブルを使用してDataFrameオブジェクトを作成する場合は、DataFrameメソッドでSQLAlchemyテーブルオブジェクトを指定します。 SQLAlchemyをMaxComputeプロジェクトに接続する方法とパラメーターの詳細については、「SQLAlchemyをMaxComputeプロジェクトに接続する」をご参照ください。 次のサンプルコードに例を示します。

from odps.df import DataFrame
import sqlalchemy

# Create a DataFrame object by using an SQLAlchemy table. 
# Set the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID to the AccessKey ID of your Alibaba Cloud account. 
# Set the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET to the AccessKey secret of your Alibaba Cloud account. 
# We recommend that you do not directly use your AccessKey ID or AccessKey secret.
conn_string = 'odps://%s:%s@<project>/?endpoint=<endpoint>' % (
    os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
)
engine = sqlalchemy.create_engine(conn_string)
metadata = sqlalchemy.MetaData(bind=engine) # Bind the metadata to a database engine. 
table = sqlalchemy.Table('pyodps_iris', metadata, extend_existing=True, autoload=True)
iris = DataFrame(table)