如何使用 pandas 基于两个分类列的组合进行 one-hot 编码?

Pet*_* H. 5 python dataframe pandas

我正在尝试用 pandas 进行一些一次性编码。输入数据如下所示:

import pandas as pd

# input data
df = pd.DataFrame({
    "pid"  : [1, 1, 2, 3],
    "code" : ["a", "b", "b", "c"],
    "time" : [0, 0, 1, 0]
})

# two of the columns are categories
df["code"] = df.code.astype("category")
df["time"] = df.time.astype("category")
Run Code Online (Sandbox Code Playgroud)

我想对列的组合进行 one-hot 编码code,并time以一种方式生成 6 列,对应于每列中类别的所有组合。在这个小示例中,将是 a_0、a_1、b_0、b_1、c_0 和 c_1。

# i've tried doing this:
df["code_time"] = df.code.astype("str") + df.time.astype("str")
del df["code"]
del df["time"]
pd.get_dummies(df, columns=["code_time"])
Run Code Online (Sandbox Code Playgroud)

但这不会给我 a_1 和 c_1 组合,因为它们没有出现在数据中。有没有简单的方法来产生我想要的输出:

df_out = pd.DataFrame({
    "pid"  : [1, 2, 3]
    "a_0"  : [1, 0, 0]
    "a_1"  : [0, 0, 0]
    "b_0"  : [1, 0, 0]
    "b_1"  : [0, 1, 0]
    "c_0"  : [0, 0, 1]
    "c_1"  : [0, 0, 0]
})
Run Code Online (Sandbox Code Playgroud)

Pet*_* H. 2

受到提交答案的启发,我最终这样做了:

# add indicator column
df["vals"] = 1

# groupby -> count -> unstack
df = (df
    .groupby(["pid", "code", "time"])
    .count()
    .unstack([1, 2])
)

df.columns = [f"{x[1]}_{x[2]}" for x in df.columns]
Run Code Online (Sandbox Code Playgroud)

它产生所需的数据帧:

>>> print(df)
     a_0  a_1  b_0  b_1  c_0  c_1
pid
1      1    0    1    0    0    0
2      0    0    0    1    0    0
3      0    0    0    0    1    0
Run Code Online (Sandbox Code Playgroud)