删除重复项,但忽略空值

2024-04-25 17:12:12 发布

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

所以我知道你可以用这样的方法删除重复行:

the_data.drop_duplicates(subset=['the_key'])

但是,如果the_key对于某些值为null,如下所示:

^{pr2}$

它将保留C列中标记的那些。有没有可能让drop_duplicates将所有nan视为不同的,并得到一个像D列一样保留数据的输出?在


Tags: the数据方法key标记datanannull
2条回答

使用与^{}链接的^{}并按^{}筛选:

df = df[(~df['the_key'].duplicated()) | df['the_key'].isna()]
#fol oldier pandas versions
#df = df[(~df['the_key'].duplicated()) | df['the_key'].isnull()]
print (df)
   the_key  C    D
1      NaN  *    *
2      NaN       * 
3    111.0  *    *

我会这样做:

dupes = the_data.duplicated(subset=['the_key'])
dupes[the_data['the_key'].isnull()] = False
the_data = the_data[~dupes]

相关问题 更多 >