python - 如何将具有不等大小和元素列表的字典转换为具有 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
我该怎么做 ?
解决方案
MultiLabelBinarizer
与d.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()
推荐阅读
- java - 为什么我的 RecyclerViewAdapter 没有显示在视图中?
- c# - 使用 NCRYPT_CERTIFICATE_PROPERTY 从智能卡中删除证书对象
- vue.js - 如何从 agggrid 中的选定行中删除蓝色
- wildfly - Wildfly 升级到 19.0.0 后,不会加载 Drools 会话
- ios - 使用 UITableViewCell 作为 HeaderView 时不显示集合视图
- python - 调用函数时,函数中相同的function_name和parameter_name会造成阻塞!谁能解释发生了什么?
- javascript - Chrome 在调用 toLocaleString 时给出错误的结果
- javascript - fullcalendar 失败的 jquery 调用
- reactjs - 如何使用 react-query 进行无限滚动?
- python-3.x - 如何根据索引提取数组中的元素?