inpute missing data based on previous value dataframe in python

You can use the fillna() method to replace missing values based on previous or next values in a pandas DataFrame. Here's an example:

main.py
import pandas as pd

# create example dataframe with missing values
df = pd.DataFrame({
    'col1': [1, 2, None, 4, None, 6],
    'col2': [None, 2, 3, None, 5, None]
})

# replace missing values with previous value in each column
df.fillna(method='ffill', inplace=True)

print(df)
281 chars
13 lines

Output:

main.py
   col1  col2
0   1.0   NaN
1   2.0   2.0
2   2.0   3.0
3   4.0   3.0
4   4.0   5.0
5   6.0   5.0
98 chars
8 lines

In this example, method='ffill' replaces the missing values with the previous value (i.e., forward fill) in each column. You can also use method='bfill' to replace missing values with the next value (i.e., backward fill).

Note that fillna() returns a new DataFrame by default, but we set inplace=True to modify the original DataFrame.

gistlibby LogSnag