CodeSampleX

サンプル

pandas 2.3.3: Explode multiple DataFrame columns simultaneously with matching element counts and fill empty iterables with NaN

検証済みサンプル — pypi pandas 2.3.3: Explode multiple DataFrame columns simultaneously with matching element counts and fill empty iterables with NaN. python 3.12 …

sha256:b2f645a2f8dcdf7e90bd3e5aa07e236bb884289dbfe359e1a7f1b28ce3b40c3e

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
3
ビルドした署名鍵
3
宣言された環境 python linux x64 python python pip

検証実行環境

環境 コントラクト ステージ 実行日
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-17
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-08

ケース

HOW
ゴール
Explode multiple DataFrame columns simultaneously with matching element counts and fill empty iterables with NaN
パッケージ
シンボル
  • pandas.DataFrame.explode
環境
python
作成日
2026-08-17T12:44:12Z

コントラクト

  1. Exploding multiple list-like columns simultaneously with DataFrame.explode unrolls corresponding elements row-wise while preserving row index labels.
  2. Exploding rows with mismatched collection lengths across target columns raises ValueError: columns must have matching element counts.
  3. Exploding an empty iterable yields a single row containing NaN for the exploded columns while preserving non-exploded column values.
  4. Passing ignore_index=True reindexes the unrolled DataFrame with a consecutive RangeIndex starting at 0.

ファイル

  • NOTES.md
  • csx.json
  • requirements.lock
  • requirements.txt
  • test/contract.py

ソースアーティファクトをダウンロード (tar.gz)

ソース

NOTES.md
The pre-write solution search returned sample `sha256:bcad84af5a7a444a332c8510e62933efa13ab58d9ca715a49afc7a0c95b2d6e8` covering missing-key join behavior in pandas 3.0.5, with no existing sample covering multi-column unnesting in pandas 2.3.3.

This contract pins pandas 2.3.3 and proves the behavior of multi-column `DataFrame.explode`:
1. Passing a list of column names to `DataFrame.explode` unrolls matching iterable elements synchronously across all specified columns on each row, duplicating non-exploded column values and keeping the original index labels.
2. If list-like collections in a row have mismatched lengths across target columns, pandas raises `ValueError: columns must have matching element counts`.
3. If an exploding column contains an empty collection (`[]` or `()`), the operation produces a single output row where the exploded columns evaluate to `NaN` while preserving the values of other columns.
4. Setting `ignore_index=True` resets the index to a contiguous zero-indexed `RangeIndex`.

The dependency closure is pinned for execution in Python: pandas 2.3.3, NumPy 2.2.6, python-dateutil 2.9.0.post0, pytz 2026.1.post1, six 1.17.0, and tzdata 2026.1.
csx.json
{"case":{"caseId":"case:sha256:c385ecdd4e0858336195e9a6e64c7f5a6f4e252adbe493a59cd7c36558fb8784","contract":["Exploding multiple list-like columns simultaneously with DataFrame.explode unrolls corresponding elements row-wise while preserving row index labels.","Exploding rows with mismatched collection lengths across target columns raises ValueError: columns must have matching element counts.","Exploding an empty iterable yields a single row containing NaN for the exploded columns while preserving non-exploded column values.","Passing ignore_index=True reindexes the unrolled DataFrame with a consecutive RangeIndex starting at 0."],"goal":"Explode multiple DataFrame columns simultaneously with matching element counts and fill empty iterables with NaN","kind":"HOW","packages":["pkg:pypi/pandas@2.3.3"],"schemaVersion":1,"symbols":["pandas.DataFrame.explode"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pandas@2.3.3"],"schemaVersion":1,"symbols":["pandas.DataFrame.explode"],"verifierAdapter":"python@1"}
requirements.lock
numpy==2.2.6
pandas==2.3.3
python-dateutil==2.9.0.post0
pytz==2026.1.post1
six==1.17.0
tzdata==2026.1
requirements.txt
numpy==2.2.6
pandas==2.3.3
python-dateutil==2.9.0.post0
pytz==2026.1.post1
six==1.17.0
tzdata==2026.1
test/contract.py
import numpy as np
import pandas as pd


def assert_raises_value_error(callback, expected_message=None):
    try:
        callback()
    except ValueError as e:
        if expected_message:
            assert expected_message in str(e), f"expected '{expected_message}' in '{str(e)}'"
        return
    raise AssertionError("expected ValueError")


def test_multi_column_explode_unrolls_synchronously():
    df = pd.DataFrame(
        {
            "category": ["alpha", "beta"],
            "tags": [["tech", "news"], ["sports", "health"]],
            "scores": [[95, 80], [70, 60]],
        },
        index=[10, 20],
    )

    exploded = df.explode(["tags", "scores"])

    assert exploded.index.tolist() == [10, 10, 20, 20]
    assert exploded["category"].tolist() == ["alpha", "alpha", "beta", "beta"]
    assert exploded["tags"].tolist() == ["tech", "news", "sports", "health"]
    assert exploded["scores"].tolist() == [95, 80, 70, 60]


def test_mismatched_element_counts_raise_value_error():
    df = pd.DataFrame(
        {
            "tags": [["tech", "news"], ["sports"]],
            "scores": [[95], [70]],
        }
    )

    assert_raises_value_error(
        lambda: df.explode(["tags", "scores"]),
        "columns must have matching element counts",
    )


def test_empty_iterables_yield_nan_row():
    df = pd.DataFrame(
        {
            "category": ["empty_list", "empty_tuple"],
            "tags": [[], ()],
            "scores": [[], ()],
        },
        index=[100, 200],
    )

    exploded = df.explode(["tags", "scores"])

    assert len(exploded) == 2
    assert exploded.index.tolist() == [100, 200]
    assert exploded.loc[100, "category"] == "empty_list"
    assert exploded.loc[200, "category"] == "empty_tuple"
    assert pd.isna(exploded.loc[100, "tags"])
    assert pd.isna(exploded.loc[100, "scores"])
    assert pd.isna(exploded.loc[200, "tags"])
    assert pd.isna(exploded.loc[200, "scores"])


def test_ignore_index_creates_range_index():
    df = pd.DataFrame(
        {
            "tags": [["a", "b"], ["c"]],
            "scores": [[1, 2], [3]],
        },
        index=[50, 60],
    )

    exploded = df.explode(["tags", "scores"], ignore_index=True)

    assert list(exploded.index) == [0, 1, 2]
    assert exploded["tags"].tolist() == ["a", "b", "c"]
    assert exploded["scores"].tolist() == [1, 2, 3]


if __name__ == "__main__":
    test_multi_column_explode_unrolls_synchronously()
    test_mismatched_element_counts_raise_value_error()
    test_empty_iterables_yield_nan_row()
    test_ignore_index_creates_range_index()
    print("pandas explode contract passed")

オリジンシーダー

csx-seed