Home > Software design >  Remove string from array using numpy
Remove string from array using numpy

Time:06-30

I have this csv with a column containing a mix of string and integer types. (ie, 6 Years and 12 Months). I am trying to find a way to convert the 'years' and 'months' into a new array containing just the months.

YrsAndMonths=np.array(['6 Years and 12 Months','7 Years and 8 Months','2 Years'])

I am trying to get an output of something like Months=['84','92','24'] Not really sure how to proceed from here.

CodePudding user response:

There is a specific approach that should work with the pattern of your sentences:

sentences = ['6 Years and 12 Months','7 Years and 8 Months','2 Years']
res = []

for x in [sentence.lower() for sentence in sentences]:
    local_res = 0
    if "year" in x:
        year = x.split("year")
        cnt = year[0]
        local_res  = int(cnt) * 12
    if "month" in x:
        month = x.split("month")[0].split("and")[1].strip()
        cnt = month
        local_res  = int(cnt)
    res.append(local_res)
    
print(res)

CodePudding user response:

This falls a bit outside of what enter image description here

  • Related