填充熊猫数据框中的缺失值

问题描述 投票:0回答:1

我有一个熊猫数据框,其中有两列:locationid,geo_loc。locationid列缺少值。

我想获取缺少的locationid行的geo_loc值,然后在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

enter image description here

我需要这样的最终输出:

enter image description here

locationid的索引1丢失,并且相应的geo_loc值为'K11'。我将在geo_loc列中查找此“ K11”,索引6的位置ID为158。使用此值我想填写索引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])))
python pandas dataframe machine-learning data-science
1个回答
0
投票

GroupBy.transform用于具有与原始大小相同的系列,并用汇总值GroupBy.transform填充:

max
© www.soinside.com 2019 - 2024. All rights reserved.