从 df 在 Python 中创建特征 table

Create a feature table in Python from a df

我有以下 df:

 id    step1 step2 step3 step4 .... stepn-1, stepn, event 
  1       a     b    c     null         null  null    1
  2       b     d    f     null         null  null    0
  3       a     d    g      h             l    m      1      

其中id是session,steps代表某条路径,event是具体的事情是否发生

我想创建一个特征存储,我们在其中采取所有可能的步骤(a、b、c、...一直到某个任意数字)并将它们作为列。然后我希望 x 列保持 id 并且如果该会话在该列中点击该步骤,它只填充 1 或零。结果如下:

id  a  b  c  d  e  f  g ... n event
 1  1  1  1  0  0  0  0     0   1
 2  0  1  0  0  0  1  0     0   0
 3  1  0  0  1  0  0  1     1   1

我有一个唯一的列表,列出了我假设将用于构建新 table 的所有可能步骤。但是在那之后,我一直在思考如何创建它。

您要查找的内容常用于机器学习,称为one-hot encoding

有一个pandas函数专门为此设计,称为pd.get_dummies()

step_cols = [c for c in df.columns if c.startswith('step')]
other_cols = [c for c in df.columns if not c.startswith('step')]

new_df = pd.get_dummies(df[step_cols].stack()).groupby(level=0).max()
new_df[other_cols] = df[other_cols]

输出:

>>> new_df
   a  b  c  d  f  g  h  l  m  id  event
0  1  1  1  0  0  0  0  0  0   1      1
1  0  1  0  1  1  0  0  0  0   2      0
2  1  0  0  1  0  1  1  1  1   3      1

可能不是最优雅的方式:

step_cols = [col for col in df.columns if col.startswith("step")]
values = pd.Series(sorted(set(df[step_cols].melt().value.dropna())))
df1 = pd.DataFrame(
    (values.isin(row).to_list() for row in zip(*(df[col] for col in step_cols))),
    columns=values
).astype(int)
df = pd.concat([df.id, df1, df.event], axis=1)

结果

df =
   id step1 step2 step3 step4  event
0   1     a     b     c   NaN      1
1   2     b     d     f   NaN      0
2   3     a     d     g     h      1

   id  a  b  c  d  f  g  h  event
0   1  1  1  1  0  0  0  0      1
1   2  0  1  0  1  1  0  0      0
2   3  1  0  0  1  0  1  1      1