python - 将 pandas 列表列转换为矩阵表示(一次热编码)

标签 python pandas list

我有一个 pandas 列,其中包含不同长度的值列表,如下所示:

  idx lists

    0 [1,3,4,5]
    1 [2]
    2 [3,5]
    3 [2,3,5]

我想将它们转换成矩阵格式,其中每个可能的值代表一列,如果该值存在则每一行填充 1,否则填充 0,如下所示:

idx  1 2 3 4 5 

  0  1 0 1 1 1
  1  0 1 0 0 0
  2  0 0 1 0 1
  3  0 1 1 0 1

我认为这是一个热编码的术语,但我尝试使用 pd.get_dummies 方法,该方法声明它可以进行单热编码,但是当我尝试如上所示提供输入时:

test_hot = pd.Series([[1,2,3],[3,4,5],[1,6]])
pd.get_dummies(test_hot)

我收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/reshape.py", line 899, in get_dummies
    dtype=dtype)
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/reshape.py", line 906, in _get_dummies_1d
    codes, levels = _factorize_from_iterable(Series(data))
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/arrays/categorical.py", line 2515, in _factorize_from_iterable
    cat = Categorical(values, ordered=True)
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/arrays/categorical.py", line 347, in __init__
    codes, categories = factorize(values, sort=False)
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/util/_decorators.py", line 178, in wrapper
    return func(*args, **kwargs)
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/algorithms.py", line 630, in factorize
    na_value=na_value)
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/algorithms.py", line 476, in _factorize_array
    na_value=na_value)
  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_labels
TypeError: unhashable type: 'list'

如果我提供单个值列表,该方法工作正常,例如:

[1,2,3,4,5]

它将显示一个 5x5 矩阵,但只用 1 填充单行。我正在尝试扩展它,以便通过提供一列列表,每行可以填充 1 个以上的值。

最佳答案

如果性能很重要,请使用 MultiLabelBinarizer:

test_hot = pd.Series([[1,2,3],[3,4,5],[1,6]])

from sklearn.preprocessing import MultiLabelBinarizer

mlb = MultiLabelBinarizer()
df = pd.DataFrame(mlb.fit_transform(test_hot),columns=mlb.classes_)
print (df)
   1  2  3  4  5  6
0  1  1  1  0  0  0
1  0  0  1  1  1  0
2  1  0  0  0  0  1

您的解决方案应更改为创建 DataFrame、 reshape 和 DataFrame.stack , 最后使用 get_dummiesDataFrame.max对于聚合:

df = pd.get_dummies(pd.DataFrame(test_hot.values.tolist()).stack().astype(int))
       .max(level=0, axis=0)

print (df)
   1  2  3  4  5  6
0  1  1  1  0  0  0
1  0  0  1  1  1  0
2  1  0  0  0  0  1

详细信息:

已创建 MultiIndex 系列:

print(pd.DataFrame(test_hot.values.tolist()).stack().astype(int))
0  0    1
   1    2
   2    3
1  0    3
   1    4
   2    5
2  0    1
   1    6
dtype: int32

调用pd.get_dummies:

print (pd.get_dummies(pd.DataFrame(test_hot.values.tolist()).stack().astype(int)))
     1  2  3  4  5  6
0 0  1  0  0  0  0  0
  1  0  1  0  0  0  0
  2  0  0  1  0  0  0
1 0  0  0  1  0  0  0
  1  0  0  0  1  0  0
  2  0  0  0  0  1  0
2 0  1  0  0  0  0  0
  1  0  0  0  0  0  1

最后聚合每个第一级的 max

关于python - 将 pandas 列表列转换为矩阵表示(一次热编码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673302/

相关文章:

python - 如何使用 Pandas 处理行对并在没有字典的情况下保留 ID 列?

python - Sympy 替代数学表达式

python - 在固定时间间隔后查找最后一个可用时间戳 - pandas 或 numpy

Pandas 饼图图删除楔形上的标签文本

c# - 获取列表中某一列上有不同的所有行

javascript - 如何从 html 中过滤掉列表元素以将其从表中消失?

Python二维列表给元素添加值

Python 3 - 将谷歌电子表格保存为 csv

python - 二维数组与一维数组比较返回二维数组

python - 根据条件使用带格式的 f 字符串