4

G'day, how can I drop the nan values without losing the whole row? This is how my df looks like.

enter image description here

I have tried the pandasdf = schule.dropna() But this deleted everything in the rows.

But I have to keep the values, because at the end, I want them to go upwards.

enter image description here

Noel Harris
  • 131
  • 1
  • 13

3 Answers3

3

it might help. you can try it !!!! enter image description here

Mohit Sharma
  • 590
  • 3
  • 10
1

As per your problem statement, you want to give less priority to nan values and bring the non-nan values to the top.

import numpy as np
import pandas as pd
import functools

def drop_and_roll(col, na_position='last', fillvalue=np.nan):
    result = np.full(len(col), fillvalue, dtype=col.dtype)
    mask = col.notnull()
    N = mask.sum()
    if na_position == 'last':
        result[:N] = col.loc[mask]
    elif na_position == 'first':
        result[-N:] = col.loc[mask]
    else:
        raise ValueError('na_position {!r} unrecognized'.format(na_position))
    return result

df = pd.read_table('data', sep='\s{2,}')

print(df.apply(functools.partial(drop_and_roll, fillvalue='')))
halfer
  • 19,824
  • 17
  • 99
  • 186
Karthick Mohanraj
  • 1,565
  • 2
  • 13
  • 28
0

Assuming you're wanting to backfill values and then drop any duplicates that appear in any of the columns this example works:

import pandas as pd
import numpy as np

data = [
    ['POINT_1.1', 'POINT_1.2', pd.NA],
    [pd.NA, pd.NA, 'POINT_1.3'],
    ['POINT_2.1', 'POINT_2.2', pd.NA],
    [pd.NA, pd.NA, 'POINT_2.3']

]

df = pd.DataFrame(data)
df

#            0          1          2
# 0  POINT_1.1  POINT_1.2       <NA>
# 1       <NA>       <NA>  POINT_1.3
# 2  POINT_2.1  POINT_2.2       <NA>
# 3       <NA>       <NA>  POINT_2.3

t = df.T.bfill().T.bfill()
t

#            0          1          2
# 0  POINT_1.1  POINT_1.2  POINT_1.3
# 2  POINT_2.1  POINT_2.2  POINT_2.3

for column in t.columns:
    t = t.drop_duplicates(column)
t

#            0          1          2
# 0  POINT_1.1  POINT_1.2  POINT_1.3
# 2  POINT_2.1  POINT_2.2  POINT_2.3



andmck
  • 101
  • 4