python-3.x - 如果找到,则在其他列中搜索第三列的字符串,然后使用 pandas 粘贴其相邻值
问题描述
我有 3 列城市、区域和密码。请注意,大多数区域都不存在于区域列中,它们存在于城市列中,因此我想使用区域和密码列填充密码
City Area Pincode
Mumbai
Pune Bandra E 123456
Bandra(W) Badalapur 789456
Bandra(E)
Badlapur Mumbai 159357
Pune 411009
我想使用城市列作为搜索字符串,因为我已经使用区域和密码列填充了 NaN 值,但是有一个城市我在密码列中看不到任何密码,因此我想使用城市列作为搜索字符串。我们可以考虑将区域和密码作为我的主表,并在这两列的帮助下填写缺少的城市密码吗?谢谢
预期产出
市区密码 Mumbai 159357 Pune Bandra E 123456 Bandra(W) Badalapur 789456 Bandra(E) 123456 Badlapur Mumbai 159357 Pune 411009
解决方案
这是你需要的。
#df.replace('?',np.nan) #use this if you indeed have '?' instead on NaN in the columns & the nuse the line below
df['Pincode']=df.groupby('Area')['Pincode'].fillna(method ='ffill')
输入
City Area Pincode
0 Mumbai Pune 411009.0
1 Pune Bandra-E 123456.0
2 Bandra(W) Badalapur 789456.0
3 Bandra(E) Bandra-W 258159.0
4 Badlapur Mumbai 159357.0
5 NaN Pune NaN
6 NaN Bandra-W NaN
输出
City Area Pincode
0 Mumbai Pune 411009.0
1 Pune Bandra-E 123456.0
2 Bandra(W) Badalapur 789456.0
3 Bandra(E) Bandra-W 258159.0
4 Badlapur Mumbai 159357.0
5 NaN Pune 411009.0
6 NaN Bandra-W 258159.0
推荐阅读
- javascript - 所需的 JSON 文件具有运行程序之前的旧值
- apache - 使用带参数的 htaccess 重写路径
- types - SBCL 注意:类型断言太复杂,无法检查
- kubernetes - 具有资源配额的 kubernetes pod 调度
- sql - Oracle - 带序列的条件插入
- android - 如何从 SharedPreference 中读取 ArrayList 键和 ArrayList 值?
- python - 如何将距离相加?
- python - 如何使用apply将python函数的多行返回到pandas数据框?
- python - 如何创建不覆盖输出 xml 的 for 循环?
- delphi - Delphi中的FastCube 2,隐藏度量的总计