0

I have this example DataFrame:

d = {'col1': [1, 2, np.NaN], 'col2': [3, np.NaN, 4], 'col3': [np.NaN, 5, 6]}
df = pd.DataFrame(data=d)

enter image description here

and want to drop NaN values in that way to get the resulting dataFrame in this shape

enter image description here

I tried to iterate over columns and use dropna() function on each column but that didn't work:

for i in columns:
    df3[i].dropna()

Next when I tried :

df = df.dropna(subset=['col1', 'col2','col3'])

I ended up with df with all rows dropped:

enter image description here

madmax80
  • 171
  • 1
  • 14

2 Answers2

1

You do not need to iterate. You can use the dropna command:

df = df.dropna(subset=['col1', 'col2'])
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
gtomer
  • 5,643
  • 1
  • 10
  • 21
1

You can do this in one line using 'dropna' of pandas. No need to iterate. Already asked here: How to remove blanks/NA's from dataframe and shift the values up

df = df.apply(lambda x: pd.Series(x.dropna().values))
Stefan
  • 897
  • 4
  • 13