AskNature
AskNature

Reputation: 115

How to replace elements in a or more list to nan by list nan's position in python3?

a = [1,2,3,np.nan,4,6,8,np.nan,5,3,7]
b = [np.nan,2,3,5,7,np.nan,6,2,6,9]

for i in np.arange(0,12,1):
    if a[i] == np.nan or b[i]==np.nan:
        a[i] = np.nan
        b[i] =np.nan

I am a newbie in python,I want the final results of:

a = [np.nan, 2,3,np.nan, 4, 6, np.nan, np.nan,5,3,7]
b = [np.nan,2,3,np.nan,7,np.nan,np.nan,2,6,9]

But it didn't work. Many thanks for any suggestion

Upvotes: 1

Views: 480

Answers (3)

Abdul Rauf
Abdul Rauf

Reputation: 54

if len(a) > len(b):
    for i, element in enumerate(b):
        if np.isnan(element) or np.isnan(a[i]):
            a[i] = np.nan
            b[i] = np.nan
else:
    for i, element in enumerate(a):
        if np.isnan(element) or np.isnan(b[i]):
            a[i] = np.nan
            b[i] = np.nan

Upvotes: 1

cs95
cs95

Reputation: 402593

You're using numpy, so why not work with numpy arrays?

a, b = map(np.array, [a, b])
l = min(a.size, b.size)
# Get a mask of NaN cells
m = np.isnan(a[:l]) | np.isnan(b[:l])
# Set to NaN based on the mask
a[:l][m] = np.nan
b[:l][m] = np.nan
a
# array([nan,  2.,  3., nan,  4., nan,  8., nan,  5.,  3.,  7.])

b
# array([nan,  2.,  3., nan,  7., nan,  6., nan,  6.,  9.])

I know this differs from OP's "expected output", but based on their explanation I think there's a bug in their output.

Upvotes: 1

Roy2012
Roy2012

Reputation: 12503

Here's a solution:

for i in range(min(len(a), len(b))):
    if np.isnan(a[i]) or np.isnan(b[i]):
        a[i] = np.NaN
        b[i] = np.NaN
        
print(a)
# [nan, 2, 3, nan, 4, nan, 8, nan, 5, 3, 7]

print(b)
# [nan, 2, 3, nan, 7, nan, 6, nan, 6, 9]

Upvotes: 0

Related Questions