Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

adding rows based on values of other rows

I have a list (in a dataframe) that looks like this:

oddnum = [1, 3, 5, 7, 9, 11, 23]

I want to create a new list that looks like this:

newlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23]
  1. I want to test if the distance between two numbers is 2 (if oddnum[index+1]-oddnum[index] == 2)

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  2. If the distance is 2, then I want to add the number following oddnum[index] and create a new list (oddnum[index] + 1)

  3. If the distance is greater than two, keep the list as is

I keep getting key error because (I think) the list runs out of [index] and [index+1] no longer exists once it reaches the end of the list. How do I do this?

>Solution :

To pass errors, the best method is to use try and except conditions. Here’s my code:

oddnum = [1, 3, 5, 7, 9, 11, 23]
res = [] # The new list
for i in range(len(oddnum)):
    res.append(oddnum[i]) # Append the first value by default
    try: # Tries to run the code
        if oddnum[i] +  2 == oddnum[i+1]: res.append(oddnum[i]+1) # Appends if the condition is met
    except: pass # Passes on exception (in our case KeyError)
print(res)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading