Pandas/Numpy: remove leading/trailing nan in a pandas series or numpy array

Viewed 413

If I have an array

a=array([nan, nan,  2.,  3.,  0., nan,  5., nan,  6.,  7.,  8., nan])

how do I trim it quickly to

array([2.,  3.,  0., nan,  5., nan,  6.,  7.,  8.])

Note that the np.nan values in the middle are left intact.

2 Answers

Try this out, just saw that @ Joe Ferndz already answer that

#series
a=pd.Series([np.nan, np.nan,  2.,  3.,  0., np.nan,  5., np.nan,  6.,  7.,  8., np.nan])
# Find out the first and last valid index and filter
a.loc[a.first_valid_index():a.last_valid_index()]

Long solution, but it works:

newarray = []
start, end = 0, len(a)  
for x in range(len(a)):
    if a[x] > 0 and start == 0: 
        start = x
        break

for x in range(len(a)):
    if a[-x] > 0 and end == len(a): 
        end = -x + 1
        break

print(a[start:end])
Related