对多个列类型的pandas数据帧执行onehot编码

2024-04-27 03:48:45 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个pandas数据帧,其中某些列有list类型的值,以及非数字和数字数据的混合列。在

示例数据

   dst_address   dst_enforcement   fwd_count ...
1  1.2.3.4       [Any,core]        8
2  3.4.5.6       []                9
3  6.7.8.9       [Any]             10
4  8.10.3.2      [core]            0

到目前为止,我已经能够通过这两行代码找出哪些列是非数字的

^{pr2}$

在所有这些非数字列中,我需要找出哪些列具有list作为数据类型,并希望对所有非数字列(包括那些列表类型)执行一次热编码

编辑:我对上述示例的预期输出如下所示

   1.2.3.4 | 3.4.5.6 | 6.7.8.9 | 8.10.3.2 | empty | Any | core | fwd_count ...
1  1         0         0         0          0       1     1      8
2  0         1         0         0          1       0     0      9
3  0         0         1         0          0       1     0      10
4  0         0         0         1          0       0     1      0    

Tags: 数据代码core示例类型pandasaddresscount
3条回答

我使用以下3个步骤:

df['dst_enforcement'] = df.dst_enforcement.apply(lambda x: x if x else ['empty'])
dm1 = pd.get_dummies(df[df.columns.difference(['dst_enforcement'])], prefix='', prefix_sep='')
dm2 = df.dst_enforcement.str.join('-').str.get_dummies('-')
pd.concat([dm1, dm2], axis=1)

Out[1221]:
   fwd_count  1.2.3.4  3.4.5.6  6.7.8.9  8.10.3.2  Any  core  empty
1          8        1        0        0         0    1     1      0
2          9        0        1        0         0    0     0      1
3         10        0        0        1         0    1     0      0
4          0        0        0        0         1    0     1      0

使用^{}取消对列表的请求,以分隔roe并调用^{}

df_new=unnesting(df,['dst_enforcement']).combine_first(df)
df_new.dst_enforcement=df_new.dst_enforcement.apply(lambda y: 'empty' if len(y)==0 else y)
m=pd.get_dummies(df_new,prefix='',prefix_sep='').groupby('fwd_count').first().reset_index()
print(m)

^{pr2}$

添加方便使用的功能:

def unnesting(df, explode):
    idx = df.index.repeat(df[explode[0]].str.len())
    df1 = pd.concat([
             pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
    df1.index = idx

    return df1.join(df.drop(explode, 1), how='left')

尝试一下:

non_numeric_cols = col_groups[np.dtype('O')]

for non in non_numeric_cols:
    print(pd.get_dummies(df[non].apply(pd.Series)))

输出:

^{pr2}$

当你既没有“Any”也没有“core”时,整行都是零。在

祝你好运。在

相关问题 更多 >