Adriano Ribeiro
Adriano Ribeiro

Reputation: 89

Move next value to first empty row pandas

Hi how do i move each value from a column to the first empty "row/cell" in pandas?

Example:

Original data:

    A   B   C
0   1  NaN  NaN
1   4    2  NaN
2   7    5  3
3 NaN  NaN  6

Desired result:
    A   B   C
0   1   2   3
1   4   5   6
2   7 NaN  NaN

Thanks!

Upvotes: 1

Views: 235

Answers (1)

Vaishali
Vaishali

Reputation: 38415

You can use sorted to align non NULL data at the top

df.apply(lambda x: sorted(x, key=pd.isnull)).dropna(how = 'all')

    A   B   C
0   1.0 2.0 3.0
1   4.0 5.0 6.0
2   7.0 NaN NaN

Upvotes: 4

Related Questions