pythonpandasdataframefillnaffill

Filling empty cells in python (import dataset from excel)


I have a dataset where I want to fill the columns and rows in python as shown below:

Dataset:

| P | Q |    
|678|1420|
|678|---|
|609|---|
|583|1260|
|---|1260|
|---|1261|
|---|1262|
|584|1263|
|---|403|
|---|---|

Expected Result:

| P | Q |
|678|1420|
|678|1420|
|609|---|
|583|1260|
|583|1260|
|583|1261|
|583|1262|
|584|1263|
|584|403|
|584|403|

I have filled the column P using fillna() but cannot do the same for column Q since the values needs to be filled for key pair.

can someone please help.


Solution

  • With your shown samples, please try following.

    df['P'] = df['P'].ffill()
    df['Q'] = df.groupby('P')['Q'].ffill()
    

    Output will be as follows:

        P        Q
    0   678.0   1420.0
    1   678.0   1420.0
    2   609.0   
    3   583.0   1260.0
    4   583.0   1260.0
    5   583.0   1261.0
    6   583.0   1262.0
    7   584.0   1263.0
    8   584.0   403.0
    9   584.0   403.0
    

    ffill documentation