Move non-empty cells to the left in pandas DataFrame

First, make function.

        def squeeze_nan(x):
            original_columns = x.index.tolist()

            squeezed = x.dropna()
            squeezed.index = [original_columns[n] for n in range(squeezed.count())]

            return squeezed.reindex(original_columns, fill_value=np.nan)

Second, apply the function.

df.apply(squeeze_nan, axis=1)

You can also try axis=0 and .[::-1] to squeeze nan to any direction.

[EDIT]

@Mxracer888 you want this?

def squeeze_nan(x, hold):
    if x.name not in hold:
        original_columns = x.index.tolist()

        squeezed = x.dropna()
        squeezed.index = [original_columns[n] for n in range(squeezed.count())]

        return squeezed.reindex(original_columns, fill_value=np.nan)
    else:
        return x

df.apply(lambda x: squeeze_nan(x, ['B']), axis=1)

enter image description here

Leave a Comment

tech