[英]pandas groupby for non missing values
I have a df like this. 我有这样的df。
>>> df
c1 t1 c2
0 NaN 20 xyz
1 NaN 20 x1y1z1
2 NaN 20 NaN
>>> df.groupby(['t1'], as_index=False).agg(lambda x: ';'.join(x.astype(str)))
t1 c1 c2
0 20 nan;nan;nan xyz;x1y1z1;nan
But I don't want to join columns values if it's np.nan 但是如果它是np.nan,我不想加入列值
desired o/p
t1 c1 c2
0 20 NaN xyz;x1y1z1
How this check can be done here? 如何在这里进行检查?
Thanks 谢谢
You could try using dropna
: 您可以尝试使用
dropna
:
df.groupby('t1', as_index=False)\
.agg(lambda x: ';'.join(x.dropna().astype(str)))\
.replace('',np.nan)
Output: 输出:
t1 c1 c2
0 20 NaN xyz;x1y1z1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.