填充数据框中缺少的值

2024-09-29 09:29:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有两列的熊猫数据框: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缺失,相应的地理位置值为“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])))

Tags: 数据iddataframenpnanlocgeopd
1条回答
网友
1楼 · 发布于 2024-09-29 09:29:24

^{}用于具有相同大小(如原始大小)的系列,由聚合值填充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函数中使用^{}技巧移除缺失的值来实现值为字符串,则字符串将按字典顺序进行比较:

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

相关问题 更多 >