1

I would like to get the not NaN values of each row and also to keep it as NaN if that row has only NaNs.

DF =

a b c
NaN NaN ghi
NaN def NaN
NaN NaN NaN
abc NaN NaN
NaN NaN NaN

The result should be like this:

Result
ghi
def
NaN
abc
NaN

1 Answers1

0

Hi there are many different solutions for this. Here is mine

import pandas as pd

data = {'a': ['NaN', 'NaN', 'NaN', 'abc', 'NaN'],
        'b': ['NaN', 'def', 'NaN', 'NaN', 'NaN'],
        'c': ['ghi', 'NaN', 'NaN', 'NaN', 'NaN']}

df = pd.DataFrame(data)

ls = []
for idx, row in df.iterrows():
    if any(x != "NaN" for x in row.unique()): # checking if there is any element which doesnt match "NaN" in the row
        mismatch = next((x for x in row.unique() if x != "NaN"), None) # if there is a mismatch get that element which mismatch "NaN"
        ls.append(mismatch)
    else:
        ls.append("NaN")

final_df = pd.DataFrame({
    "result":ls
})
>>> print(final_df)

result
0   ghi
1   def
2   NaN
3   abc
4   NaN
Rukon
  • 77
  • 5