pandas 分组依据,并找到所有列的第一个非空值 [英] pandas group by and find first non null value for all columns

查看:58
本文介绍了 pandas 分组依据,并找到所有列的第一个非空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的熊猫DF如下,

id  age   gender  country  sales_year
1   None   M       India    2016
2   23     F       India    2016
1   20     M       India    2015
2   25     F       India    2015
3   30     M       India    2019
4   36     None    India    2019

我想对ID进行分组,按照sales_date的要求,使用最新的1行(所有非null元素).

I want to group by on id, take the latest 1 row as per sales_date with all non null element.

预期输出

id  age   gender  country  sales_year
1   20     M       India    2016
2   23     F       India    2016
3   30     M       India    2019
4   36     None    India    2019

在pyspark中,

df = df.withColumn('age', f.first('age', True).over(Window.partitionBy("id").orderBy(df.sales_year.desc())))

但是我需要在大熊猫中使用相同的解决方案.

But i need same solution in pandas .

EDIT ::所有列都可能出现这种情况.不只是年龄.我需要它为所有id拾取最新的非null数据(id存在).

EDIT :: This can the case with all the columns. Not just age. I need it to pick up latest non null data(id exist) for all the ids.

推荐答案

使用如果 sales_year 列未排序:

df2 = df.sort_values('sales_year', ascending=False).groupby('id', as_index=False).first()
print (df2)
   id   age gender country  sales_year
0   1  20.0      M   India        2016
1   2  23.0      F   India        2016
2   3  30.0      M   India        2019
3   4  36.0    NaN   India        2019

这篇关于 pandas 分组依据,并找到所有列的第一个非空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆