Python 3.x 搜索其他列中第三列的字符串(如果找到),并使用熊猫粘贴其相邻值

Python 3.x 搜索其他列中第三列的字符串(如果找到),并使用熊猫粘贴其相邻值,python-3.x,pandas,Python 3.x,Pandas,我有3列:城市、地区和pincode。请注意,大多数区域都不在区域列中,而在城市列中,所以我想使用区域和pincode列填充pincode City Area Pincode Mumbai Pune Bandra E 123456 Bandra(W) Badalapur 789456 Bandra(E) Badlapur

我有3列:城市、地区和pincode。请注意,大多数区域都不在区域列中,而在城市列中,所以我想使用区域和pincode列填充pincode

City            Area            Pincode 
Mumbai                      
Pune            Bandra E        123456
Bandra(W)       Badalapur       789456
Bandra(E)       
Badlapur        Mumbai          159357
                Pune             411009


我想使用city列作为搜索字符串,因为我已经使用area和pincode列填充了NaN值,但有一个城市在pincode列中没有看到任何pincodes,因此我想使用city列作为搜索字符串。我们可以把区域和密码作为我的主表,并借助这2个栏填充城市丢失的密码吗?谢谢

预期产量

城区Pincode 孟买159357 浦那班德拉123456 班德拉(西)巴达拉普尔789456 班德拉(东)123456 孟买巴德拉普159357 浦那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
输出

      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

从样本数据来看,似乎在最后第二条记录中,对于普纳市,area和pincode两列都有NaN。你想两个都填吗?最后一条记录也是一样。我想使用城市列作为搜索字符串,如果在区域列中找到,并且给出了pin,则填充区域列缺少的值。城市的查找表在哪里?程序无法知道普纳是一个城市还是一个地区。是的,没有办法知道,但是如果城市列中的地区与区域列中的地区匹配,那么我们也会得到这些地区的pincodes,否则不会。至少我们会得到一些pincode。我想使用city列作为搜索字符串,因为我已经使用area和pincode列填充了NaN值,但有一个城市的pincode列中没有看到任何pincodes,因此我想使用city列作为搜索字符串。我们可以把区域和密码作为我的主表,并借助这2个栏填充城市丢失的密码吗?谢谢你能提供传达你意图的数据吗?根据您提供的数据,只需使用“区域”,我们就可以填充“?”腐生物。我已经更新了问题。我还注意到,在我的数据中,大多数面积不在面积列中,但它们在城市列中,因此面积列中没有面积,因此NaN值。因此,借助城市列,我们可以用共点填充NaN值吗?谢谢