在熊猫数据框中填充缺少的值

时间:2020-02-22 09:43:32

标签: python pandas dataframe machine-learning data-science

我有一个熊猫数据框,其中有两列: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])))

1 个答案:

答案 0 :(得分:2)

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     B16