1

Assume, I have a Pandas DataFrame as following:

|    0 |   1 |   2 |   3 |
|-----:|----:|----:|----:|
| 1115 | nan | "YE"| nan |
| 1590 | nan | "He"| "NO"|

How can I rearrange such a DataFrame consisting of over 100 columns and rows, that the nan values are shifted to the right side and the real values to the left side:

Desired output:

|    0 |   1 |   2 |   3 |
|-----:|----:|----:|----:|
| 1115 | "YE"| nan | nan |
| 1590 | "HE"| "NO"| nan |

Note: this should also work for an arbitrary number of columns and rows.

EchoCache
  • 555
  • 2
  • 8
  • 22
  • Related to [the justify function](https://stackoverflow.com/questions/44558215/python-justifying-numpy-array/44559180#44559180) – Quang Hoang Mar 28 '20 at 02:16

1 Answers1

2

IIUC

df=df.T.apply(lambda x : sorted(x,key=pd.isnull)).T
      0    0     1    2
0  1115  "YE"   NaN  NaN
1  1590  "He"  "NO"  NaN
BENY
  • 317,841
  • 20
  • 164
  • 234