我正在做一些房地产数据清理工作,遇到了这个新手问题,令人惊讶的是我自己无法解决。
我有这个数据帧,在lat和lon列中具有nan值。我可以算出输入给定邻域的lat和lon平均值的几乎正确的值。
这是一个示例,实际的DF有超过2万行。
lat lon neighborhood
-34.62 -58.50 Monte Castro
-34.63 -58.36 Boca
nan nan San Telmo
我用以下代码制作了两个带有lat和lon意思的字典,用于每个邻域:
neighborhood_lat = []
neighborhood_lon = []
for neighborhood in df['l3'].unique():
lat = df[((df['l3']==neighborhood) & (df['lat'].notnull()))].mean().lat
lon = df[((df['l3']==neighborhood) & (df['lon'].notnull()))].mean().lon
neighborhood_lat.append({neighborhood: lat})
neighborhood_lon.append({neighborhood: lon})
这是其中一项命令的一部分:
neighborhood_lat
[{'Mataderos': -34.65278757721805},
{'Saavedra': -34.551813882357166},
{nan: nan},
{'Boca': -34.63204552441155},
{'Boedo': -34.62695442446412},
{'Abasto': -34.603728937455315},
{'Flores': -34.62757516061659},
{'Nuñez': -34.54843158034983},
{'Retiro': -34.595564030955934},
{'Almagro': -34.60692879236826},
{'Palermo': -34.58274909271148},
{'Belgrano': -34.56304387233704},
{'Recoleta': -34.592081482406854},
{'Balvanera': -34.608665174550694},
{'Caballito': -34.61749059613885}
然后我试图用这些词典填充lat和lon,但是我不明白如何为fillna设置条件,以便根据邻居lat和lon的意思填充lat和lon。
预期结果
lat lon neighborhood
-34.62 -58.50 Monte Castro
-34.63 -58.36 Boca
(mean lat of neighborhood) (mean lon of neighborhood) San Telmo
感谢您的帮助。
答案 0 :(得分:0)
再次回答我自己的问题...
我在此答案的帮助下找到了解决该问题的正确代码: answer
代码:
创建字典:
neighborhood_lat = {}
neighborhood_lon = {}
for neighborhood in df['l3'].unique():
neighborhood_lat[neighborhood] = df[((df['l3']==neighborhood) & (df['lat'].notnull()))].mean().lat
neighborhood_lon[neighborhood] = df[((df['l3']==neighborhood) & (df['lon'].notnull()))].mean().lon
用字典填充nan值:
df['lat'] = df['lat'].fillna(df['l3'].map(neighborhood_lat))
df['lon'] = df['lon'].fillna(df['l3'].map(neighborhood_lon))