python - 如何对 pandas 列中的列表执行一次热编码?

标签 python pandas list

假设我有一个数据框,其中一列是一个列表(具有未知的值和长度),例如:

df = pd.DataFrame(
 {'messageLabels': [['Good', 'Other', 'Bad'],['Bad','Terrible']]}
)

我遇到了这个解决方案,但它不是我要找的。 How best to extract a Pandas column containing lists or tuples into multiple columns

理论上生成的 df 看起来像

messageLabels             | Good| Other| Bad| Terrible
--------------------------------------------------------
['Good', 'Other', 'Bad']  | True| True |True| False
--------------------------------------------------------
['Bad','Terrible']        |False|False |True| True

见上文

最佳答案

简洁

df.join(df.messageLabels.str.join('|').str.get_dummies().astype(bool))

        messageLabels   Bad   Good  Other  Terrible
0  [Good, Other, Bad]  True   True   True     False
1     [Bad, Terrible]  True  False  False      True

sklearn

from sklearn.preprocessing import MultiLabelBinarizer

mlb = MultiLabelBinarizer()
dum = mlb.fit_transform(df.messageLabels)

df.join(pd.DataFrame(dum.astype(bool), df.index, mlb.classes_))

        messageLabels   Bad   Good  Other  Terrible
0  [Good, Other, Bad]  True   True   True     False
1     [Bad, Terrible]  True  False  False      True

过度

n = len(df)
i = np.arange(n)
l = [*map(len, df.messageLabels)]
j, u = pd.factorize(np.concatenate(df.messageLabels))

o = np.zeros((n, len(u)), bool)
o[i.repeat(l), j] = True

df.join(pd.DataFrame(o, df.index, u))

        messageLabels   Good  Other   Bad  Terrible
0  [Good, Other, Bad]   True   True  True     False
1     [Bad, Terrible]  False  False  True      True

乱搞

并受到 Andy 的启发

df.join(pd.DataFrame([dict.fromkeys(x, True) for x in df.messageLabels]).fillna(False))

        messageLabels   Bad   Good  Other  Terrible
0  [Good, Other, Bad]  True   True   True     False
1     [Bad, Terrible]  True  False  False      True

关于python - 如何对 pandas 列中的列表执行一次热编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56298815/

相关文章:

python - 不断收到 python ModuleNotFoundError : No module named

python - settings.py 文件中的 Django AttributeError

python - hdf5 文件到 pandas 数据框

python - 如何从列表中返回一组值的索引以获取该组中的特定值?

Python 3 : Flatten Dictionary including lists

java - 如何使用 Stream 从嵌套列表中获取符合特定条件的所有列表?

python - Django Queryset 和 filter() 与 get()

python - 使用串口通过 Arduino 将多个值发送到 Raspberry

python - 如何将 Pandas Dataframe 中的字符串转换为列表或字符数组?

Python:如何检查变量的最后三个数字是否为 000?