如何在一次热编码后聚合行

2024-05-19 02:11:50 发布

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

如何在应用一个热编码后聚合结果? 下面是我的样本数据

df= pd.DataFrame([
    ['apple','sweet'],
    ['apple','affordable'],
    ['apple','fruit'],
    ['orange','fruit'],
    ['orange','soup'],
    ['orange','cheap'],
    ['orange','sweet'],
    ['soda','sweet'],
    ['soda','cheap'],
    ['soda','softdrinks']
    ])

df= df.rename(columns={0: "productName", 1: "itemFeatures"})

我试过了

df_ohe = pd.get_dummies(df['itemFeatures'])
df_ohe_merged = pd.concat([df, df_ohe],axis='columns')
df_final = df_ohe_merged.drop(['itemFeatures'],axis='columns')

如何获得如下所示的期望输出? 还是有更好的办法

desired_output = pd.DataFrame([
    ['apple',1,0,0,1,0,0,1],
    ['orange',0,1,0,1,0,1,1],
    ['soda',0,0,1,0,1,0,1]
])
desired_output = desired_output.rename(columns={0: "productName",
                                                1: "affordable",
                                                2: "cheap",
                                                3: "famous",
                                                4: "fruit",
                                                5: "softdrinks",
                                                6: "sour",
                                                7: "sweet",
                                               })

非常感谢


Tags: columnsappledataframedfoutputpdsweetfruit
1条回答
网友
1楼 · 发布于 2024-05-19 02:11:50

使用^{}

new_df = pd.crosstab(df['productName'],df['itemFeatures'],colnames = [None]).reset_index()

另一种方法是^{}

new_df = (df.pivot_table(index = 'productName',
                         columns = 'itemFeatures',
                         aggfunc = 'size',
                         fill_value = 0)
            .reset_index()
            .rename_axis (columns = None))
print(new_df)

  productName  affordable  cheap  fruit  softdrinks  soup  sweet
0       apple           1      0      1           0     0      1
1      orange           0      1      1           0     1      1
2        soda           0      1      0           1     0      1

相关问题 更多 >

    热门问题