用与z不同的最后一个值替换零

2024-04-18 11:43:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

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

我怎么能做到?你知道吗


Tags: 数据dfdtprodfinalinventoryprintop
2条回答

想法是用^{}替换0到nan,然后用以前的非缺失值向前填充它们:

cols = df.columns.difference(['dt_op'])
df[cols] = df[cols].mask(df[cols] == 0).ffill().astype(int)

^{}类似的解决方案:

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)

相关问题 更多 >