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如下:
| ID | Country | Trades |
|---|---|---|
| P11 | France | 5 |
| P12 | Germany | 3 |
| P13 | UK | 7 |
| P14 | Croatia | 13 |
| P15 | USA | 5 |
| P16 | UK | 2 |
内容的提问来源于stack exchange,提问作者vegetarian_python
相关产品推荐
相关产品推荐

