通过从pandas datafram中的所有非nan合并相同的索引行

2024-04-25 19:09:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有重复索引的稀疏数据帧。如何合并相同的索引行,使冲突行中的所有非NaN数据保持不变?在

我知道,使用内置的drop_duplicates函数可以实现非常接近的目标,但只能使用相同的索引保留第一行行或最后一行

df.reset_index().drop_duplicates(subset='index', keep='first').set_index('index').sort_index()

我需要的是来自任何冲突行的所有非nan值。在

在此之前:

DataFrame with A,B,C,D columns, and 1,2,2,3,4,5 rows. In the first 2-indexed row there is a 2.0 in the B column, in the second, there is a 3.0 in the D column.

之后:

enter image description here


Tags: 数据函数目标dfindexnansort内置

热门问题