我有以下数据框,其中包含示例值,例如:-
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_sep
和 prefix
添加到 get_dummies
然后,如果只需要 1
或 0
值(虚拟值或指标列),则使用 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_dummies
和 max
并最后添加 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/