python - 从另一个数据框中的列中发现信息
问题描述
我有两个数据框,它们是 df_First:
df_First = pd.DataFrame({'Car Model': ['Fiesta 2010', 'Fiesta 2010', 'Cruze 2020', 'Fiesta
2005'],
'Car Plate End': [749, 749, 100, 200],
'Car Color': ['Red', 'Red', 'Blue', 'Black'],
'Num Door': [2,2,4,4]})
print(df_First)
Car Model Car Plate End Car Color Num Door
Fiesta 2010 749 Red 2
Fiesta 2010 749 Red 2
Cruze 2020 100 Blue 4
Fiesta 2005 200 Black 4
和 df_Second:
df_Second = pd.DataFrame({'Car Plate End': [749, 749, 749, 100, 749, 100, 200, 500],
'Cost_Max': [10, 20, 30, 40, 50, 60, 70, 80],
'Cost_Min': [1, 2, 3, 4, 5, 6, 7, 8]})
print(df_Second)
Car Plate End Cost_Max Cost_Min
749 10 1
749 20 2
749 30 3
100 40 4
749 50 5
100 60 6
200 70 7
500 80 8
我想创建一个新的数据框(与 df_Second 的行数相同)。它必须包含基于车牌末端的车型。
所需的输出如下:
Car Plate End Cost_Max Cost_Min Car Model
749 10 1 Fiesta 2010
749 20 2 Fiesta 2010
749 30 3 Fiesta 2010
100 40 4 Cruze 2020
749 50 5 Fiesta 2010
100 60 6 Cruze 2020
200 70 7 Fiesta 2005
500 80 8 NaN
我试图实现以下代码:
df_Total = pd.merge(df_Second, df_First, on=['Car Plate End'], how='outer')
然而,我的离开并不如愿。输出是:
Car Plate End Cost_Max Cost_Min Car Model Car Color Num Door
749 10 1 Fiesta 2010 Red 2.0
749 10 1 Fiesta 2010 Red 2.0
749 20 2 Fiesta 2010 Red 2.0
749 20 2 Fiesta 2010 Red 2.0
749 30 3 Fiesta 2010 Red 2.0
749 30 3 Fiesta 2010 Red 2.0
749 50 5 Fiesta 2010 Red 2.0
749 50 5 Fiesta 2010 Red 2.0
100 40 4 Cruze 2020 Blue 4.0
100 60 6 Cruze 2020 Blue 4.0
200 70 7 Fiesta 2005 Black 4.0
500 80 8 NaN NaN NaN
我只需要找出 df_Second 所指的汽车型号。我不需要其他列。我还希望 df_Total 具有与 df_Second 相同的行数。非常感谢您的帮助和关注。
解决方案
要解决的主要问题是您的第一个数据框包含需要删除的重复关系。有几种方法可以实现结果,包括merge
, join
, map
。这是join
方法,
map_unique = df_First.groupby('Car Plate End')['Car Model'].first()
df_Second.join(map_unique, on='Car Plate End')
推荐阅读
- git - Git - 使用系统代理
- php - 无法构建 Dockerfile - 无法找到包
- asp.net-core - 如何共享由主机管理但租户可以访问的实体?
- apache-spark - 如何在 PySpark DataFrame 中强制进行特定分区?
- ios - UITextfield 弹跳文本
- javascript - 后端分析结束时调用函数或渲染组件
- mysql - 我可以通过触发器将数据从 MySql 插入到 MongoDB 中吗?
- javascript - 如何在js中生成以下组合
- ros - rosbag record -a - 不收集包文件
- php - 如何使用 POST 请求保存一组值?(WordPress API)