python - 如果在 Pandas 中删除重复项时,如果一列的值不是 None,则保留行
问题描述
给定一个玩具数据框如下:
id type name purpose
1 retail tower a sell
retail tower a rent
office t1 sell
2 office t1 rent
retail t2 sell
retail t2 rent
retail s1 sell
5 office s1 rent
我想根据子集列删除重复项,type
而name
不是保留first
或last
( ),如果列不是df.drop_duplicates(subset = ['type', 'name'], keep= 'last')
,我希望保留该行。id
None
预期的结果将是这样的:
id type name purpose
1 retail tower a sell
2 office t1 rent
retail t2 rent
retail s1 sell
5 office s1 rent
我怎么能在 Python 中做到这一点?谢谢。
解决方案
您可以通过测试非缺失值来创建帮助列,更改行的顺序iloc
并通过最大值获取索引,这意味着最后一个非错误DataFrameGroupBy.idxmax
,最后传递到loc
:
idx = df.assign(tmp = df['id'].notna()).iloc[::-1].groupby(['type','name'])['tmp'].idxmax()
df = df.loc[idx.iloc[::-1]]
print (df)
id type name purpose
0 1.0 retail tower a sell
3 2.0 office t1 rent
5 NaN retail t2 rent
6 NaN retail s1 sell
7 5.0 office s1 rent
如果要保留第一个值:
idx = df.assign(tmp = df['id'].notna()).groupby(['type','name'], sort=False)['tmp'].idxmax()
df = df.loc[idx]
print (df)
id type name purpose
0 1.0 retail tower a sell
3 2.0 office t1 rent
4 NaN retail t2 sell
6 NaN retail s1 sell
7 5.0 office s1 rent
推荐阅读
- word-wrap - Python Reportlab:将西里尔文文本包装到表格单元格中
- ssis - SQL Server 集成包失败并出现非描述错误。在 VS2019 中工作,但不能从命令行使用 DTEXEC
- python - Plotly:如何使用 plotly.graph_objects 将两个 3D 图放在同一个图上?
- php - 从 WooCommerce 中的 $order->get_formatted_line_subtotal() 获取非格式化值
- python - 在线程中更改全局变量
- azure - 微服务架构中的通知服务
- c++ - 嵌套的未定义行为能否消除初始未定义行为的(潜在)危险?
- mongodb - mongocxx::options::find 的运行时错误
- ios - iOS swift socket通信:释放outstream
- java - ActiveMQ 消费者未能在请求队列上消费消息