pandas - 在不同列的重复项中保留具有最高值的行
问题描述
我有一个像这样的 pandas 数据框,其中我可以有相同的 long 和 lat 组合的行:
初始df:
lon lat name value protection a b c score
0 20 10 canada 563 NaN cat dog elephant 20.0
1 30 10 canada 65 NaN lion tiger cat 30.0
2 40 20 canada 893 NaN dog NaN NaN 20.0
3 40 20 usa 4 NaN horse horse lion 40.0
4 45 15 usa 8593 NaN NaN lion cat 10.0
5 20 10 protection1 100 medium NaN NaN NaN NaN
6 40 20 protection1 20 high NaN NaN NaN NaN
7 50 30 protection1 500 low NaN NaN NaN NaN
但我想要的是:
想要的输出:
lon lat protection a b c score
0 20 10 medium cat dog elephant 20.0
1 30 10 NaN lion tiger cat 30.0
2 40 20 high horse horse lion 40.0
3 45 15 NaN NaN lion cat 10.0
4 50 30 low NaN NaN NaN NaN
输出数据框应包含具有唯一组合的行long
和lat
列,其中仅score
保留最高的行,但如果long
和lat
具有重复项和protection
列中的值,则应将它们合并为一个
解决方案
尝试:
df = df.sort_values(by="score", ascending=False)
g = df.groupby(["lon", "lat"])
df_out = (
g.first()
.assign(
protection=g.agg(
{"protection": lambda x: ",".join(x.dropna())}
).replace("", np.nan)
)
.reset_index()
)
print(df_out)
印刷:
lon lat name value protection a b c score
0 20 10 canada 563 medium cat dog elephant 20.0
1 30 10 canada 65 NaN lion tiger cat 30.0
2 40 20 usa 4 high horse horse lion 40.0
3 45 15 usa 8593 NaN NaN lion cat 10.0
4 50 30 protection1 500 low NaN NaN NaN NaN
推荐阅读
- tensorflow - 使用 Tensorflow + Keras 的对象检测项目(根架构)。用于准确训练模型的图像样本大小?
- excel - 将工作簿中的多张工作表保存到新工作簿中
- python - Python - 使用请求时发布请求失败
- node.js - 使用 Node.js 将大量文件上传到 Google Storage 存储桶
- powershell - Adding Open Type Fonts to a Private Font Collection using Add Font File method
- ruby-on-rails - Ruby on Rails 和 Redis:未初始化的常量 Redis::Namespace
- java - 给出不一致答案的 2 个日历实例之间的差异
- objective-c - 我应该如何将数据发送到 iOS 中的套接字
- python - SQL 数据库是否比大型 Pandas 数据框更节省内存/性能?
- python - 导入但未使用的问题“Tkinter as tk”