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

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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