DataFrame の操作#

pandas.DataFramepolars.DataFrame をお使いの方へ。デフォルトでは、すべての scikit-learn および chemotools 変換器は numpy.ndarray を出力します。しかし、現在では chemotools の前処理メソッドを設定して、 pandas.DataFrame または polars.DataFrame オブジェクトを出力として生成することが可能です。これは scikit-learn の新しい set_output() API の実装により可能になりました( pandas の場合 >= 1.2.2、 polars の場合 >= 1.4.0)(ドキュメント)。 StandardScaler() など、他の scikit-learn 前処理メソッドに実装されているものと同じ API が、 chemotools 変換器でも利用可能になりました。

注釈

バージョン 0.1.3 以降、すべての chemotools 関数で set_output() が利用可能です!

以下に、この新しい API の使用方法を示す 2 つの例を紹介します:

例 1: 単一の前処理メソッドでの set_output() API の使用#

1. スペクトルデータを pandas.DataFrame として読み込む#

まず、スペクトルデータを読み込みます。ここでは、各行がスペクトルを表し、各列が波数を表す spectra.csv というファイルを想定します。

import pandas as pd
from chemotools.baseline import AirPls

# Load your data as a pandas DataFrame
spectra = pd.read_csv('data/spectra.csv', index_col=0)

spectra 変数は pandas.DataFrame オブジェクトで、インデックスはサンプル名を表し、列は波数を表します。

2. chemotools 前処理オブジェクトを作成し、出力を pandas に設定する#

次に、 AirPls オブジェクトを作成し、出力を pandas に設定します。

# Create an AirPLS object and set the output to pandas
airpls = AirPls().set_output(transform='pandas')

set_output() メソッドは以下の引数を受け付けます:

  • transform : 出力フォーマット。 'pandas' または 'default' を指定できます(デフォルトフォーマットは numpy.ndarray を出力します)。

ヒント

出力を polars に設定したい場合は、 set_output() メソッドで transform='polars' を使用します( AirPLS().set_output(transform='polars') )。

3. スペクトルをフィットして変換する#

# Fit and transform the spectra
spectra_airpls = airpls.fit_transform(spectra)

fit_transform() メソッドの出力は、 pandas.DataFrame オブジェクトになります。

ヒント

デフォルトでは、入力データのインデックスと列は出力に維持されず、 spectra_airpls DataFrame はデフォルトのインデックスと列を持つことに注意してください。

例 2: パイプラインでの set_output() API の使用#

同様に、 set_output() API はパイプラインでも使用できます。以下のコードは、次の処理を実行するパイプラインの作成方法を示しています:

  • 乗法散乱補正

  • 標準スケーリング

import pandas as pd
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from chemotools.scatter import MultiplicativeScatterCorrection

# Make the pipeline
pipeline = make_pipeline(MultiplicativeScatterCorrection(), StandardScaler())

# Set the output to pandas
pipeline.set_output(transform="pandas")

# Fit the pipeline and transform the spectra
output = pipeline.fit_transform(spectra)

ヒント

出力を polars に設定したい場合は、 set_output() メソッドで transform='polars' を使用します( pipeline.set_output(transform='polars') )。