繁体   English   中英

如果使用 Pandas 在另一行的两列中匹配,则替换一行中的缺失值

[英]Replace missing value in a row if there's a match in two columns from another row using Pandas

我正在做一个数据分析项目,我有以下 dataframe 看起来像这样。

ID 店铺 纬度
1 一个 1 -4
2 2 3
3 C 4 5
4 D 2 3

我想用 id 为 4 的行中的一个填充“store”列中的缺失值 NaN,因为 id 为 2 和 4 的行在“long”和“lat”列中具有相同的值,因此 output 应该看起来像这样

ID 店铺 纬度
1 一个 1 -4
2 D 2 3
3 C 4 5
4 D 2 3

我想为长 dataframe (几乎一百万行)执行此操作,所以我不知道具有相同“long”和“lat”值的行 ID。

我正在使用 Pandas 研究 Python。 我只使用for 循环和 iterrows() 提出了这个解决方案,这非常慢

df_missing_names = df[df['store'].isna()] #rows that have missing names
df_with_names = df[df['store'].notna()] #rows that don't have missing names

for indx, row in df_missing_names.iterrows(): #run through all the rows that don't have names

    for indx_j, row_j in df_with_names.iterrows(): #run through all the rows that have names

        if (row.lat == row_j.lat) & (row.long == row_j.long): #if both lat and long values match
            df[indx, 'store'] = row_j.store #then update name of the row in the original dataframe

有没有更快的方法使用 Pandas 上的内置函数来执行此操作? 谢谢您的帮助

您可以使用:

df['store'] = df.groupby(['long', 'lat'], sort=False).bfill()['store']

Output:

   id store  long  lat
0   1     A     1   -4
1   2     D     2    3
2   3     C     4    5
3   4     D     2    3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM