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

Pandas DataFrame按CustomerNr去重并保留Period1、Period2有效值如何实现

实现代码

你可以直接对CustomerNr列分组后,对其余列取首个非空值实现需求,完整代码如下:

import numpy as np
import pandas as pd

df = pd.DataFrame([[1001, 120,np.nan], [1001,np.nan ,30], [1004, 160,np.nan],[1005, 160,np.nan], 
                   [1006,np.nan ,8], [1010, 160,np.nan],[1010,np.nan ,4]], columns=['CustomerNr','Period1','Period2'])

# 核心处理逻辑
result = df.groupby('CustomerNr', as_index=False).agg('first')
print(result)

代码说明

  • groupby('CustomerNr'):按客户编号分组,相同客户编号的行会被分到同一组
  • agg('first'):对每个分组内的每一列,取第一个非空值,正好匹配合并保留重复行非空有效值的需求
  • as_index=False:指定客户编号不作为结果的索引,保留为普通列

运行后输出的result就是目标结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:36:02