gpt4 book ai didi

pandas - 如何在 Pandas 中应用一种热编码或在两列上一起使用假人?

转载 作者:行者123 更新时间:2023-12-04 10:44:40 25 4
gpt4 key购买 nike

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

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 然后使用 max如果只想要 10值(虚拟或指标列)或 sum如果需要计数 1值(value)观:

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 中应用一种热编码或在两列上一起使用假人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59763877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com