首页 > 解决方案 > 如果找到,则在其他列中搜索第三列的字符串,然后使用 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

标签: python-3.xpandas

解决方案


这是你需要的。

#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

推荐阅读