I need copy the value "a" lower and next I would like that the value of "b" will be also copied lower so many times until it encounters another value etc until the end of column 1
I tried to iterate through the rows and add conditions, unfortunately I wasn't get the result as I want. My dataframe looks like:
| col1 | col2 | col3 |
|---|---|---|
| a | ||
| x1 | x2 | |
| b | ||
| y1 | y2 | |
| p1 | p2 | |
| c | ||
| q1 | q2 | |
| ... | ... | ... |
Result as I want:
| col1 | col2 | col3 |
|---|---|---|
| a | ||
| a | x1 | x2 |
| b | ||
| b | y1 | y2 |
| b | p1 | p2 |
| c | ||
| c | q1 | q2 |
| ... | ... | ... |
CodePudding user response:
Use pandas.fillna with method=ffill:
When used on a column, this replaces the NaN values in a given row with non-NAN values preceding the row.
import pandas as pd
data = pd.DataFrame({"col1": [1, None, 2, None, None, 3, None, 4, 5, None, None]})
data["col1"] = data["col1"].fillna(method="ffill")
print(data)
Output:
col1
0 1.0
1 1.0
2 2.0
3 2.0
4 2.0
5 3.0
6 3.0
7 4.0
8 5.0
9 5.0
10 5.0
OR
Use pandas.ffill which works similar to above solution and looks more clean. Both the methods mentioned so far allows in place replacement of values.
Using ffill method: df['col1'].ffill(inplace=True).
