我在 Python 中有一个数据框和一个字典,如下所示,我需要根据字典过滤数据框。如您所见,字典的键和值是数据框的两列。我想要一个数据框的子集,其中包含字典的键和值以及其他列。
df:
字典是:
d = {
40275: ['Book','Software'],
39900: ['Book'],
35886: ['Software'],
40350: ['Software'],
28129: ['Software']
}
我需要以下数据框:
最佳答案
展开字典并创建一个新的数据框,然后将内部merge
df
与新的数据框
df.merge(pd.DataFrame([{'Customer_ID': k, 'Category': i}
for k, v in d.items() for i in v]))
Customer_ID Category Type Delivery
0 40275 Book Buy True
1 40275 Software Sell False
2 39900 Book Buy True
3 35886 Software Sell False
4 40350 Software Sell True
5 28129 Software Buy False
https://stackoverflow.com/questions/69961068/
相关文章:
haskell - 如何使用 `zipTree` 实现 `foldTree` ?
awk - 使用 grep 或 awk 查找 txt 和 csv 文件之间的匹配行
intellij-idea - 如何将项目从 IDEA 连接到 Gitlab
flutter - 无法将类型为 'String' 的值分配给 flutter Getx 中类型为
javascript - 如何在 react-native 中结合使用 Drawer Navigat
typescript - @typescript-eslint/naming-convention