如何对多个 pandas 数据框中存在的列进行热编码?

问题描述 投票:0回答:1

我有来自十个不同冰球赛季的事件级数据的十个数据框,每个数据框都有几列,我想对它们进行热编码,目的是根据历史数据训练模型以对今年的数据进行预测。我当前的问题是需要编码的列不包含每个数据帧中的所有可能值。举个例子,添加了一些扩展团队,因此早年的数据帧不会有这些团队,因此它们不会有编码列。

我尝试的第一件事是连接所有十个数据帧并以这种方式进行我的一个热编码,但是我的数据帧变得太大并且我的 jupyter 笔记本内核不断死亡。所以现在我决定尝试单独处理每个数据帧,但这给我带来了我上面解释的问题,并且我很难找到解决方案。这是我正在寻找的示例。我希望表 1 和表 2 成为一个热编码,如下所示。

表1

团队
A 1
B 1

表2

团队
B 2
C 2

表1一热编码

团队 A B C
A 1 1 0 0
B 1 0 1 0

表2一热编码

团队 A B C
B 2 0 1 0
C 2 0 0 1

本质上问题是,我如何获得表 1 中的“C”列和表 2 中的“A”列,因为这些值在这些表中不存在。

python-3.x pandas dataframe
1个回答
0
投票

您需要确保拥有跨 DataFrame 的所有独特团队的集合,并从那里开始工作。 那么你可以...

A.在

pandas.get_dummies
列上运行
'team'
,然后将
.reindex
缺失的队伍放入结果中

import numpy as np
import pandas as pd

df1 = pd.DataFrame({'team': ['a', 'b'], 'year': [1, 1]})
df2 = pd.DataFrame({'team': ['b', 'c'], 'year': [2, 2]})
teams = np.union1d(df1['team'].unique(), df2['team'].unique())

df1_encoded = pd.get_dummies(df1['team']).reindex(columns=teams, fill_value=False).astype(int)
df2_encoded = pd.get_dummies(df2['team']).reindex(columns=teams, fill_value=False).astype(int)

print(df1.join(df1_encoded))
#   team  year  a  b  c
# 0    a     1  1  0  0
# 1    b     1  0  1  0

print(df2.join(df2_encoded))
#   team  year  a  b  c
# 0    b     2  0  1  0
# 1    c     2  0  0  1

B.将团队列转换为分类列,

pandas.get_dummies
将提供正确的结果

import numpy as np
import pandas as pd

df1 = pd.DataFrame({'team': ['a', 'b'], 'year': [1, 1]})
df2 = pd.DataFrame({'team': ['b', 'c'], 'year': [2, 2]})

# Convert each Team column to a Categorical that share the same categories
TeamsDtype = pd.CategoricalDtype(
    np.union1d(df1['team'].unique(), df2['team'].unique())
)
df1['team'] = df1['team'].astype(TeamsDtype)
df2['team'] = df2['team'].astype(TeamsDtype)

# `get_dummies` *works* now with no extra contortion
df1_encoded = pd.get_dummies(df1['team']).astype(int)
df2_encoded = pd.get_dummies(df2['team']).astype(int)

print(df1.join(df1_encoded))
#   team  year  a  b  c
# 0    a     1  1  0  0
# 1    b     1  0  1  0

print(df2.join(df2_encoded))
#   team  year  a  b  c
# 0    b     2  0  1  0
# 1    c     2  0  0  1

如果您要坚持

'team'
列,我推荐后者,分类方法 以其原始形式,因为分类编码将加速任何比较操作并减少数据的内存占用。

© www.soinside.com 2019 - 2024. All rights reserved.