我有一个任务,需要清理重复记录的数据,但同时用 nan 填充这些单元格,例如具有相同名称的记录的值:
id id2 name other_n date country
1.177.002 nan test_name nan 8 decembre 1981 usa
1.177.002 A test_name ALVA nan nan
到目前为止,我尝试了普通的 groupby 但没有得到我预期的结果
tst.groupby('name').mean()
tst.groupby('name').sum()
我正在寻找的结果应该是这样的:
id id2 name other_n date country
1.177.002 A test_name ALVA 8 decembre 1981 usa
最佳答案
运行:
df.groupby('name', as_index=False)\
.agg(lambda col: col.loc[col.first_valid_index()])\
.reindex(df.columns, axis=1)
需要最后的重新索引才能将列顺序恢复到原来的样子 它们在源 DataFrame 中排序。否则名称将被移动 到第一名
关于python - 对数据进行分组以完成彼此之间的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60009573/