我有一个包含两列的pandas数据帧: locationid、geo_loc。locationid列缺少值。
我想要获取丢失的位置id行的Locationid值,然后在geo_loc列中搜索这个geo_loc值并获取位置id。
df1 = pd.DataFrame({'locationid':[111, np.nan, 145, np.nan, 189,np.nan, 158, 145],
'geo_loc':['G12','K11','B16','G12','B22','B16', 'K11',he l 'B16']})
df

我需要如下所示的最终输出:

位置is的索引%1丢失,相应的geo_loc值为'K11‘。我会在geo_loc列中查找这个'K11‘,索引6有locationid158。我想用这个值来填充索引1中缺失的值。
我试过这些代码,但它们不起作用。
df1['locationid'] = df1.locationid.fillna(df1.groupby('geo_loc')['locationid'].max())df1['locationid'] = df1.locationid.fillna(df1.groupby('geo_loc').apply(lambda x: print(list(x.locationid)[0])))发布于 2020-02-22 17:45:48
对具有相同大小的序列使用GroupBy.transform,如由聚合值max填充的原始序列
df1['locationid']=df1.locationid.fillna(df1.groupby('geo_loc')['locationid'].transform('max'))
print (df1)
locationid geo_loc
0 111.0 G12
1 158.0 K11
2 145.0 B16
3 111.0 G12
4 189.0 B22
5 145.0 B16
6 158.0 K11
7 145.0 B16如果通过在lambda函数中使用Series.dropna删除缺失的值是可能的,字符串将按字典顺序进行比较:
df1 = pd.DataFrame({'locationid':[111, np.nan, 145, np.nan, 189,np.nan, 158, 145],
'geo_loc':['G12','K11','B16','G12','B22','B16', 'K11', 'B16']})
#sample data strings with missing values
df1['locationid'] = df1['locationid'].dropna().astype(str) + 'a'
df1['locationid']= (df1.groupby('geo_loc')['locationid']
.transform(lambda x: x.fillna(x.dropna().max())))
print (df1)
locationid geo_loc
0 111.0a G12
1 158.0a K11
2 145.0a B16
3 111.0a G12
4 189.0a B22
5 145.0a B16
6 158.0a K11
7 145.0a B16https://stackoverflow.com/questions/60350862
复制相似问题