pandas - 如何在 pandas 中应用一种热编码或在 2 列上同时获取虚拟值?

标签 pandas one-hot-encoding

我有以下数据框,其中包含示例值,例如:-

df = pd.DataFrame([["London", "Cambridge", 20], ["Cambridge", "London", 10], ["Liverpool", "London", 30]], columns= ["city_1", "city_2", "id"])

city_1     city_2        id
London     Cambridge     20
Cambridge  London        10
Liverpool  London        30

我需要如下输出数据帧,该数据帧是在将 2 个城市列连接在一起并随后应用一种热编码时构建的:

id London Cambridge Liverpool
20 1       1        0
10 1       1        0
30 1       0        1

目前,我正在使用下面的代码,该代码在某一列上运行一次,请您告知是否有任何 pythonic 方法来获取上述输出

output_df = pd.get_dummies(df, columns=['city_1', 'city_2'])

结果

id city_1_Cambridge city_1_London and so on columns

最佳答案

您可以将参数 prefix_sepprefix 添加到 get_dummies然后,如果只需要 10 值(虚拟值或指标列),则使用 max;如果需要计数,则使用 sum 1 值:

output_df = (pd.get_dummies(df, columns=['city_1', 'city_2'], prefix_sep='', prefix='')
               .max(axis=1, level=0))
print (output_df)
   id  Cambridge  Liverpool  London
0  20          1          0       1
1  10          1          0       1
2  30          0          1       1

或者,如果想要处理没有 id 的所有列,则首先将不处理列转换为索引 DataFrame.set_index ,然后使用 get_dummiesmax 并最后添加 DataFrame.reset_index :

output_df = (pd.get_dummies(df.set_index('id'), prefix_sep='', prefix='')
               .max(axis=1, level=0)
               .reset_index())
print (output_df)
   id  Cambridge  Liverpool  London
0  20          1          0       1
1  10          1          0       1
2  30          0          1       1

关于pandas - 如何在 pandas 中应用一种热编码或在 2 列上同时获取虚拟值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59763877/

相关文章:

python - Pandas get_dummies 为同一特征生成多个列

tensorflow - 混合 one_hot 和 float 输入

python - += 更新 pandas datadame 中的行

python - 如何将 Pandas 数据框中的字符串值替换为整数?

python - 使用循环 Python Pandas 将数据帧子集为单独的数据帧

python - 使用 DataFrame 对象时,plot_2d_separator 会提示(引发 AttributeError)

python - 使用 onehot 编码的 Tensorflow 嵌入查找

python - Pytorch 将张量转换为一个热

python-3.x - OneHotEncoder 的功能名称

python - 根据列表排序数据框,匹配 Pandas 中的一列