为了账号安全,请及时绑定邮箱和手机立即绑定

用零填充行其他列有一些值,否则其他列没有值在python pandas中用NaN填充

用零填充行其他列有一些值,否则其他列没有值在python pandas中用NaN填充

喵喔喔 2022-07-12 09:34:13
我有如下数据框import pandas as pdimport numpy as npk={'ID':[1,2,3,4,5,6],'m1':[20,'',30,40,50,60],   'm2':['',40,40,90,'',''],   'm3':['','','','','',''],   'm4':['','','','','',''],   'm5':['','','','',1,''],   'm6':[10,'','',90,'','']}df=pd.DataFrame(data=k)我们检查了同一行的其他行中是否有任何退出值,然后我们需要用零填充它,或者其他确实包含我们必须填充的任何值,NAN我的结果显示如下ID  m1  m2  m3  m4  m5  m61   20  0.0 0.0 0.0 0.0 10.0 # first row and last row has value some vale so  we have fill it Zero others rows  2   0   40.0    NaN NaN NaN NaN  # there are no value after the second row we have will it with NAN3   30  40.0    NaN NaN NaN NaN  # there are no value after the second row we have will it with NAN4   40  90.0    0.0 0.0 0.0 90.0 # first row,second row  and last row has some value so we have fill it Zero to other rows  5   50  0.0 0.0 0.0 1.0 NaN   # first row,and fifth row has some value so we have fill it Zero to other rows and last row with Nan  6   60  NaN NaN NaN NaN NaN # there are no value after the first row we have will it with NAN
查看完整描述

1 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

让我们bfill尝试mask


s=df.iloc[:,1:]

df.iloc[:,1:]=s.mask(s.mask(s=='').bfill(1).notna()&(s==''),0)

df

   ID  m1  m2 m3 m4 m5  m6

0   1  20   0  0  0  0  10

1   2   0  40             

2   3  30  40             

3   4  40  90  0  0  0  90

4   5  50   0  0  0  1    

5   6  60             


查看完整回答
反对 回复 2022-07-12
  • 1 回答
  • 0 关注
  • 86 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号