使用pandas填充数据框中的缺失值

我有一个包含两个列的pandas数据框:locationid和geo_loc。locationid列中有缺失值。

我想获取缺失locationid行的geo_loc值,然后在geo_loc列中搜索这个geo_loc值,并获取相应的locationid。

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处的locationid是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])))

回答:

使用GroupBy.transform为与原始大小相同的Series填充聚合值max

df1['locationid']=df1.locationid.fillna(df1.groupby('geo_loc')['locationid'].transform('max'))print (df1)   locationid geo_loc0       111.0     G121       158.0     K112       145.0     B163       111.0     G124       189.0     B225       145.0     B166       158.0     K117       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']})#包含缺失值的字符串样本数据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_loc0     111.0a     G121     158.0a     K112     145.0a     B163     111.0a     G124     189.0a     B225     145.0a     B166     158.0a     K117     145.0a     B16

Related Posts

如何对SVC进行超参数调优?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

如何在初始训练后向模型添加训练数据?

我想在我的scikit-learn模型已经训练完成后再…

使用Google Cloud Function并行运行带有不同用户参数的相同训练作业

我正在寻找一种方法来并行运行带有不同用户参数的相同训练…

加载Keras模型,TypeError: ‘module’ object is not callable

我已经在StackOverflow上搜索并阅读了文档,…

在计算KNN填补方法中特定列中NaN值的”距离平均值”时

当我从头开始实现KNN填补方法来处理缺失数据时,我遇到…

使用巨大的S3 CSV文件或直接从预处理的关系型或NoSQL数据库获取数据的机器学习训练/测试工作

已关闭。此问题需要更多细节或更清晰的说明。目前不接受回…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注