熊猫分组并找到所有列的第一个非空值

j '*_*j ' 5 python group-by window pandas pyspark

我有熊猫 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
Run Code Online (Sandbox Code Playgroud)

我想按 id 分组,根据 sales_date 取最新的 1 行,所有非空元素。

预期输出,

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
Run Code Online (Sandbox Code Playgroud)

在pyspark中,

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

但我需要在熊猫中相同的解决方案。

编辑:: 所有列都是这种情况。不仅仅是年龄。我需要它为所有 id 获取最新的非空数据(id 存在)。

jez*_*ael 9

使用GroupBy.first

df1 = df.groupby('id', as_index=False).first()
print (df1)
   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
Run Code Online (Sandbox Code Playgroud)

如果列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
Run Code Online (Sandbox Code Playgroud)