加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 用n-1替换缺失值

发布时间:2020-12-20 11:07:31 所属栏目:Python 来源:网络整理
导读:例如:我有, df = pd.DataFrame({0: [420,np.nan,455,np.nan]})df 00 420.01 NaN2 455.03 NaN4 NaN5 NaN 然后使用: df[0].isnull().astype(int)0 01 12 03 14 15 1Name: 0,dtype: int64 我明白了 df[0].fillna(method='ffill') - df[0].isnull().astype(int
例如:我有,

df = pd.DataFrame({0: [420,np.nan,455,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,2,3,然后到最后:

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

细节

定义组

df[0].notna().cumsum()

0    1
1    1
2    2
3    2
4    2
5    2
Name: 0,dtype: int64

在groupby中使用cumcount

df.groupby(df[0].notna().cumsum()).cumcount()

0    0
1    1
2    0
3    1
4    2
5    3
dtype: int64

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读