Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete all nan values from list in pandas dataframe

if any elements are there along with nan then i want to keep element and want to delete nan only like

example 1 ->

index      values
0     [nan,'a',nan,nan]

output should be like

index   values

0         [a]

example 2->

index      values
0     [nan,'a',b,c]

1     [nan,nan,nan]

output should be like

index   values

0      [a,b,c]

1        [] 
like image 333
Shubham Thagunna Avatar asked Dec 14 '22 15:12

Shubham Thagunna


1 Answers

This is one approach using df.apply.

import pandas as pd
import numpy as np

df = pd.DataFrame({"a": [[np.nan, np.nan, np.nan, "a", np.nan], [np.nan, np.nan], ["a", "b"]]})
df["a"] = df["a"].apply(lambda x: [i for i in x if str(i) != "nan"])
print(df)

Output:

        a
0     [a]
1      []
2  [a, b]
like image 163
Rakesh Avatar answered Feb 03 '23 02:02

Rakesh