[英]pandas group by and find first non null value for all columns
我有熊猫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 存在)。
使用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
如果列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
利用 -
df.dropna(subset=['gender']).sort_values('sales_year', ascending=False).groupby('id')['age'].first()
输出
id
1 20
2 23
3 30
4 36
Name: age, dtype: object
删除['age']
以获得完整的行 -
df.dropna().sort_values('sales_year', ascending=False).groupby('id').first()
输出
age gender country sales_year
id
1 20 M India 2015
2 23 F India 2016
3 30 M India 2019
4 36 None India 2019
您可以使用reset_index()
将id
作为一列放回 -
df.dropna().sort_values('sales_year', ascending=False).groupby('id').first().reset_index()
输出
id age gender country sales_year
0 1 20 M India 2015
1 2 23 F India 2016
2 3 30 M India 2019
3 4 36 None India 2019
print(df.replace('None',np.NaN).groupby('id').first())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.