[英]Replace zeros with last value different from zero
我有以下数据帧:
print(inventory_df)
dt_op Prod_1 Prod_2 Prod_n
1 10/09/18 5 50 2
2 11/09/18 4 0 0
3 12/09/18 2 0 0
4 13/09/18 0 0 0
5 14/09/18 4 30 1
我想将值更改为零,使用最后一个值!=从零开始,在每列中,如下所示:
print(final_inventory_df)
dt_op Prod_1 Prod_2 Prod_n
1 10/09/18 5 50 2
2 11/09/18 4 50 2
3 12/09/18 2 50 2
4 13/09/18 2 50 2
5 14/09/18 4 30 1
我怎么能这样做?
想法是通过mask
将0
替换为NaN,然后通过先前的非缺失值向前填充它们:
cols = df.columns.difference(['dt_op'])
df[cols] = df[cols].mask(df[cols] == 0).ffill().astype(int)
与numpy.where
类似的解决方案:
df[cols] = pd.DataFrame(np.where(df[cols] == 0, np.nan, df[cols]),
index=df.index,
columns=cols).ffill().astype(int)
print (df)
dt_op Prod_1 Prod_2 Prod_n
1 10/09/18 5 50 2
2 11/09/18 4 50 2
3 12/09/18 2 50 2
4 13/09/18 2 50 2
5 14/09/18 4 30 1
有趣的解决方案 - 无需dt_op
即可转换为整数所有列:
d = dict.fromkeys(df.columns.difference(['dt_op']), 'int')
df = df.mask(df == 0).ffill().astype(d)
另一种选择:
df.iloc[:,1:] = df.iloc[:,1:].replace(0, np.nan).ffill().astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.