for ループを使用して複数の商品情報を取得し、それらを concat して一つの DataFrame にまとめるコード

2024年6月23日

了解しました。for ループを使用して複数の商品情報を取得し、それらを concat して一つの DataFrame にまとめるコードの例を以下に示します。

python
import requests
import pandas as pd

def 商品情報取得(shop_url, access_token, product_handle):
    # APIエンドポイントの構築
    endpoint = f'{shop_url}/admin/api/2022-01/products.json?handle={product_handle}'

    # ヘッダーの設定
    headers = {
        'Content-Type': 'application/json',
        'X-Shopify-Access-Token': access_token
    }

    # APIリクエストの実行
    response = requests.get(endpoint, headers=headers)

    # レスポンスのステータスを確認
    if response.status_code == 200:
        # レスポンスから商品情報を抽出
        product_id = response.json()['products'][0]['id']

        # 商品情報を格納するDataFrameの作成
        df = pd.DataFrame({
            '商品ID': [product_id],
            '商品ハンドル': [product_handle]
        })

        # 商品IDを表示し、DataFrameを返す
        print(f'商品ID: {product_id}')
        return df
    else:
        # リクエストが成功しなかった場合はエラーメッセージを表示
        print(f'エラー: {response.status_code}n{response.text}')
        return None  # または必要に応じて例外を発生させる

# 使用例: 複数の商品ハンドル
商品ハンドルリスト = ['商品ハンドル1', '商品ハンドル2', '商品ハンドル3']

# 空のDataFrameを作成
結果のDataFrame = pd.DataFrame()

# 各商品ハンドルに対して商品情報を取得し、結果のDataFrameにconcat
for handle in 商品ハンドルリスト:
    商品情報_df = 商品情報取得(shop_url, access_token, handle)
    if 商品情報_df is not None:
        結果のDataFrame = pd.concat([結果のDataFrame, 商品情報_df], ignore_index=True)

# 結果のDataFrameを表示
print(結果のDataFrame)

この例では、商品ハンドルリスト に複数の商品ハンドルを指定し、それぞれの商品情報を取得して結果の DataFrame に concat しています。ignore_index=True を指定することで、新しい DataFrame が作成されます。

未分類

Posted by ぼっち