Search code examples
pythonpandasindexingfillna

How to fill a specific position missing value in pandas Dataframe


I have a pandas Dataframe with 15 x 15 dimensions.

I am trying to fill the missing values using if statement. I want to fill the mirrored position of filled values. For example, if z.values[0, 0] == 1 then I want to fill the z.values[15, 15] value equal to 0 and vise versa. I am using this code:

    if z.values[0, 0] == 1:
        z.values[15, 15].fillna() == 0
    else:
        z.values[15, 15].fillna() == 1

Note: This is just for z.values[0, 0] I also want all the indexing to have the above mentioned coding using a for loop or something else.


Solution

  • You could first invert your dataframe by reversing the index and columns:

    >>> df2 = df.loc[df.index[::-1], df.columns[::-1]]
    

    Then, we replace 0s with 1s and 1s with 0s:

    >>> df2 = df2.replace({0: 1, 1: 0})
    

    Now, use those values to fill your datafrme only where the value is currently null:

    >>> df[df.isnull()] = df2.values
    

    For example, for this sample input:

        F4   F3   F2   F1
    F4   1  1.0  1.0  1.0
    F3   0  1.0  1.0  NaN
    F2   1  1.0  NaN  NaN
    F1   1  NaN  NaN  NaN
    

    The output is this:

        F4   F3   F2   F1
    F4   1  1.0  1.0  1.0
    F3   0  1.0  1.0  0.0
    F2   1  1.0  0.0  1.0
    F1   1  0.0  0.0  0.0