【发布时间】:2020-03-21 17:12:59
【问题描述】:
我有熊猫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 行,所有非空元素。
预期输出,
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())))
但我在 pandas 中需要相同的解决方案。
编辑 :: 这可以适用于所有列。不仅仅是年龄。我需要它来获取所有 id 的最新非空数据(id 存在)。
【问题讨论】:
-
你的输出仍然包含
None值,除非我遗漏了什么 -
如果行中没有任何有效数据,则 None 很好。但如果可用,它应该检测示例中 id 1 的方式,年龄从第二个替换最高年份数据。
标签: python pandas group-by pyspark window