给出以下序列:
[I、Z、S、I、I、J、N、J、I]
并给出以下 Pandas 数据框:
char fricative nasal lateral labial coronal dorsal frontal
I 0 0 0 0 0 0 1
J 0 0 1 0 1 0 1
N 0 1 0 0 0 1 0
S 1 0 0 0 1 0 0
Z 1 0 0 0 1 0 0
如何将序列中的每个字符映射到数据框中各自的一个热向量?
最佳答案
用途:
df = df.set_index("char")
res = df.loc[sequence, :].to_numpy().tolist()
输出
[[0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 1, 0, 1], [0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1]]
更新
如果您还需要事件类别,您可以使用 bool 掩码直接索引到列,如下所示:
df = df.set_index("char")
res = [df.columns[row.astype(bool)].tolist() for row in df.loc[sequence, :].to_numpy()]
print(res)
输出
[['frontal'], ['fricative', 'coronal'], ['fricative', 'coronal'], ['frontal'], ['frontal'], ['lateral', 'coronal', 'frontal'], ['nasal', 'dorsal'], ['lateral', 'coronal', 'frontal'], ['frontal']]
关于python - 将类映射到 Pandas 一种热门编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69822337/