Python/pandas

[Python] Pandas Reshape

Owen.white 2022. 10. 14. 10:41
728x90
반응형

목차

    Reshaping

    Stack

    tuples = list(
        zip(
            ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
            ["one", "two", "one", "two", "one", "two", "one", "two"],
        )
    )
    
    index = pd.MultiIndex.from_tuples(tuples, names = ["first", "second"])
    
    df = pd.DataFrame(np.random.randn(8, 2), index = index, columns = ["A", "B"])
    
    df2 = df[:4]
    
    df2

    stack() 메소드는 데이터 프레임의 열에서 레벨을 '압축'한다.

    stacked = df2.stack()
    
    stacked

    "스택된" 데이터 프레임 또는 시리즈(인덱스로서 멀티인덱스를 갖는)의 경우, stack()의 역연산은 stack()이며, 기본적으로 마지막 레벨은 unstack 된다.

    stacked.unstack()

    stacked.unstack(1)

    stacked.unstack(0)

    Pivot tables

    df = pd.DataFrame(
        {
            "A": ["one", "one", "two", "three"] * 3,
            "B": ["A", "B", "C"] * 4,
            "C": ["foo", "foo", "foo", "bar", "bar", "bar"] * 2,
            "D": np.random.randn(12),
            "E": np.random.randn(12),
        }
    )
    df

    pivot_table()은 값, 인덱스 및 열을 지정하는 데이터 프레임을 피벗한다.

    pd.pivot_table(df, values = "D", index = ["A", "B"], columns = ["C"])

     

    반응형