You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python DataFrame去重:保留非NULL行,移除含NULL重复行

处理DataFrame中含NULL的重复行问题

场景说明:有一个包含ID、Country、Trades三列的DataFrame,部分行除了Country字段可能为NULL外,其余字段完全重复。需要保留Country非空的行,移除对应的NULL重复行(重复行顺序不固定,NULL行可能在非空行之前或之后)。

构造示例数据

先还原示例DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'ID': ['P11', 'P12', 'P13', 'P13', 'P14', 'P15', 'P15', 'P16', 'P16'],
    'Country': ['France', 'Germany', 'UK', np.nan, 'Croatia', 'USA', np.nan, 'UK', np.nan],
    'Trades': [5, 3, 7, 7, 13, 5, 5, 2, 2]
})

解决方案

提供两种可行的处理方式:

方式一:排序后去重

先调整行顺序,让Country非空的行排在前面,再按重复字段去重保留第一行:

# 排序:Country非空行优先,NULL行后置
df_sorted = df.sort_values(by='Country', na_position='last')
# 按ID和Trades去重,保留第一个出现的行(即非空行)
cleaned_df = df_sorted.drop_duplicates(subset=['ID', 'Trades'], keep='first')

方式二:分组筛选

按重复字段分组,每组内直接筛选出Country非空的行(兼容无重复NULL行的情况):

def filter_non_null(group):
    non_null_rows = group[group['Country'].notna()]
    return non_null_rows if not non_null_rows.empty else group

cleaned_df = df.groupby(['ID', 'Trades'], group_keys=False).apply(filter_non_null)

清洗后结果

最终得到的DataFrame如下:

IDCountryTrades
P11France5
P12Germany3
P13UK7
P14Croatia13
P15USA5
P16UK2

内容的提问来源于stack exchange,提问作者vegetarian_python

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 09:42:41