【发布时间】:2021-12-13 17:29:25
【问题描述】:
鉴于以下数据存储在文本文件中:
fricative f, s, S, x, v, z, Z, G, h
nasal n, m, N
lateral r, l, j, J
labial p, b, m, f, v
coronal s, z, n, d, t, r, l, j, J, S, Z
dorsal g, k, G, x, N, h
frontal e, i, I, E, E:, E~, j, J,
如何创建一个单热编码函数,将单个字母放在第一列,并且在每个字母前面有一个描述现有标签的单热编码:
| letters | fricative | nasal | lateral | labial | coronal | dorsal | frontal |
|---|---|---|---|---|---|---|---|
| e | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
| f | 1 | 0 | 0 | 1 | 0 | 0 | 1 |
| g | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
| j | 0 | 0 | 1 | 0 | 1 | 0 | 1 |
我查看了this link,但可以使用如下自定义函数:
def one_hot_labels(df):
'''
- for each line, create a dictionary indicating the presence (1)
or the absence (0) of every label
- put the dictionaries in the list and convert it to a data frame
'''
dict_labels = []
for i in (range(len(df)), leave=False):
d = dict(zip(range(n_labels), [0]*n_labels))
...
dict_labels.append(d)
df_labels = pd.DataFrame(dict_labels)
return df_labels
【问题讨论】:
-
那么
fricative和f, s, S,...是列名吗? -
@QuangHoang 感谢您的回复。我刚刚修复了表格,列名是
fricative nasal lateral labial coronal dorsal frontal第一个列是字母,所以每行都是一个向量,如果列标题(即标签)存在则为 1,如果列标题(标签)不存在则为 0 .示例 row2f 1 0 0 1 0 0 1表示字母f是擦音、唇音和额音。
标签: python pandas dataframe one-hot-encoding