1/19/2022

pandas replace zeros with previous non zero value

 

Here, our example data is stock csv file.


Load data and print 

.

import pandas as pd
IBM_path = 'IBM-practice.csv'
df = pd.read_csv(IBM_path, delimiter=',', usecols=['Date', 'Open', 'High', 'Low', 'Close', 'Volume'])
print(df)

.

         Date        Open        High         Low       Close    Volume

0  2021-01-19  123.594643  123.891014  122.456978  123.346077   5646308

1  2021-01-20  123.996178  125.296364  122.906311  124.359467        10

2  2021-01-21  124.397705  126.424477  124.330788  125.860420         0

3  2021-01-22  115.391968  115.391968  112.198853  113.393883  39814421

4  2021-01-25  113.537285  114.282982  112.284897  113.365204  14315974

5  2021-01-26  113.938812  117.198853  113.212234  117.103249  11186656



replace zeros with previous non zero value & check

.

# Replace 0 to avoid dividing by 0 later on
df['Volume'].replace(to_replace=0, method='ffill', inplace=True)
print(df)

.

         Date        Open        High         Low       Close    Volume

0  2021-01-19  123.594643  123.891014  122.456978  123.346077   5646308

1  2021-01-20  123.996178  125.296364  122.906311  124.359467        10

2  2021-01-21  124.397705  126.424477  124.330788  125.860420        10

3  2021-01-22  115.391968  115.391968  112.198853  113.393883  39814421

4  2021-01-25  113.537285  114.282982  112.284897  113.365204  14315974

5  2021-01-26  113.938812  117.198853  113.212234  117.103249  11186656


Thank you.

www.marearts.com

πŸ™‡πŸ»‍♂️


No comments:

Post a Comment