首页 > 解决方案 > 如何将具有不等大小和元素列表的字典转换为具有 1 和 0 值的 Dataframe

问题描述

我在用着python 3.7.6

我有一本字典如下:

key   - string
value - list of strings

值(列表)的大小不同

例如:

 {'GP': ['col_1', 'col_2', 'col_3', 'col_4'], 
 'MIN': ['col_1', 'col_2', 'col_3', 'col_4'],
 'PTS': ['col_1', 'col_2', 'col_3', 'col_4'], 
 'FGM': ['col_1', 'col_2', 'col_4'], 
 'FGA': ['col_2'], 
 'FG%': ['col_2', 'col_3', 'col_4'],
 '3P Made': ['col_2', 'col_3'], 
 'AST': ['col_2', 'col_3'], 
 'STL': ['col_2'], 
 'BLK': ['col_2', 'col_3'],
 'TOV': ['col_3']}

我想将此字典转换为Dataframe,其中键是行,列是列表值,内容是 1 或 0(取决于行是否具有列表值):

            col_1       col_2       col_3    col_4  
 GP           1         1           1           1
 MIN          1         1           1           1 
 PTS          1         1           1           1 
 FGM          1         1           0           1 
 FGA          0         1           0           0 
 FG%          0         1           1           1
 3P Made      0         1           1           0
 AST          0         1           1           0
 STL          0         1           0           0
 BLK          0         1           1           0
 TOV          0         0           1           0

我该怎么做 ?

标签: pythonpandas

解决方案


MultiLabelBinarizerd.keys()d.values()字典一起使用:

from sklearn.preprocessing import MultiLabelBinarizer

mlb = MultiLabelBinarizer()
df = pd.DataFrame(mlb.fit_transform(d.values()), index=d.keys(),columns=mlb.classes_)
print (df)
         col_1  col_2  col_3  col_4
GP           1      1      1      1
MIN          1      1      1      1
PTS          1      1      1      1
FGM          1      1      0      1
FGA          0      1      0      0
FG%          0      1      1      1
3P Made      0      1      1      0
AST          0      1      1      0
STL          0      1      0      0
BLK          0      1      1      0
TOV          0      0      1      0

Pandas 唯一的解决方案,但使用Series,Series.str.join和时速度较慢Series.str.get_dummies

df = pd.Series(d).str.join('|').str.get_dummies()

推荐阅读