用n

编程入门 行业动态 更新时间:2024-10-18 12:25:27
本文介绍了用n-1替换缺失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如:我有

df = pd.DataFrame({0: [420, np.nan, 455, np.nan, np.nan, np.nan]}) df 0 0 420.0 1 NaN 2 455.0 3 NaN 4 NaN 5 NaN

然后使用:

df[0].isnull().astype(int) 0 0 1 1 2 0 3 1 4 1 5 1 Name: 0, dtype: int64

我知道

df[0].fillna(method='ffill') - df[0].isnull().astype(int) 0 420.0 1 419.0 2 455.0 3 454.0 4 454.0 5 454.0 Name: 0, dtype: float64

我想要得到0,1,0,1,2,3,然后最后:

I am looking for to get 0,1,0,1,2,3, then in the end :

df [0] = 420、419、455; 454,453,452

df[0]= 420, 419, 455; 454,453, 452

推荐答案

groupby,cumcount

df[0].ffill() - df.groupby(df[0].notna().cumsum()).cumcount() 0 420.0 1 419.0 2 455.0 3 454.0 4 453.0 5 452.0 dtype: float64

详细信息 定义组

Details Define groups

df[0].notna().cumsum() 0 1 1 1 2 2 3 2 4 2 5 2 Name: 0, dtype: int64

与cumcount一起在groupby中使用

Use in groupby with cumcount

df.groupby(df[0].notna().cumsum()).cumcount() 0 0 1 1 2 0 3 1 4 2 5 3 dtype: int64

更多推荐

用n

本文发布于:2023-11-29 12:00:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646342.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!