将零替换为不等于零的最后一个值

Ale*_*lli 2 python pandas

我有以下数据帧:

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
Run Code Online (Sandbox Code Playgroud)

我想将值更改为零,使用最后一个值!=从零开始,在每列中,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做?

jez*_*ael 5

想法被替换0为NaNs mask,然后通过以前的非缺失值转发它们:

cols = df.columns.difference(['dt_op'])
df[cols] = df[cols].mask(df[cols] == 0).ffill().astype(int)
Run Code Online (Sandbox Code Playgroud)

类似的解决方案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
Run Code Online (Sandbox Code Playgroud)

有趣的解决方案 - 无需转换为整数所有列dt_op:

d = dict.fromkeys(df.columns.difference(['dt_op']), 'int')
df = df.mask(df == 0).ffill().astype(d)
Run Code Online (Sandbox Code Playgroud)