我有一个列表字典,例如,

dictionary_test = {'A': ['hello', 'byebye', 'howdy'], 'B': ['bonjour', 'hello', 'ciao'], 'C': ['ciao', 'hello', 'byebye']}

我想将其转换为 bool 隶属矩阵以供进一步分析。最好将 keys 作为列名,并将项目列为行名:
         A    B    C
  hello  1    1    1
 byebye  1    0    1
  howdy  1    0    0
bonjour  0    1    0
   ciao  0    1    1

是否可以在 Python 中进行(最好是这样我可以将矩阵写入 .csv 文件)?
我想这是我必须用 numpy 做的事情,对吗?

另一个问题是字典的大小是未知的(键的数量和列表中的元素数量都不同)。

最佳答案

您可以使用 pandas 。这是一个例子。

>>> import pandas as pd
>>> dictionary_test = {'A': ['hello', 'byebye', 'howdy'], 'B': ['bonjour', 'hello', 'ciao'], 'C': ['ciao', 'hello', 'byebye']}
>>> values = list(set([ x for y in dictionary_test.values() for x in y]))
>>> data = {}
>>> for key in dictionary_test.keys():
...  data[key] = [ True if value in dictionary_test[key] else False for value in values ]
...
>>> pd.DataFrame(data, index=values)
             A      B      C
ciao     False   True   True
howdy     True  False  False
bonjour  False   True  False
hello     True   True   True
byebye    True  False   True

如果您想要按特定顺序排列的行。只需手动设置 values

关于python - bool 矩阵形式 Python 的列表字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41964618/

10-12 23:39
查看更多