0

I have two for loops that goes through all my dataframe. The goal is to calculate the slope between 2 points on the same line, until the slope reaches 2 or higher. Then it continues on the next row. It goes like this :

step = 0.3
#debut = []

for n in range (ncol-1):
    for m in range (nline):
        slope = (df.iat[m, (n + 1)] - df.iat[m, n])/step
        if slope < 2:
            n = n + 1
        else:
            #tuple(debut)
            debut = list(n)
            m = m + 1
            n = 0
    if m > (nline):
        break

My dataframe is basic data with an header and a line index.

I want to keep track of the value of 'n', for each row, when it reaches the 2 or higher slope. I tried the debut = list(n) without success. The list I want would go like this:

1     'column 1 header'
2     'column 2 header' 
3     'column 3 header' 
...
Mat17
  • 67
  • 2
  • 9

1 Answers1

0

As @Nullman suggested, using append to add the column number to your list is the proper approach. However, there seem to be other issues with your code. You're using n and m in your for loops as iterators (which will automatically increment them) and also manually incrementing/resetting them. The order of your loops is also inverted from what your description would apply (looping over rows and then columns vs columns and then rows).

step = 0.3
debut = []

for m in range (nline):
    for n in range (ncol-1)
        slope = (df.iat[m, (n + 1)] - df.iat[m, n])/step
        if slope >= 2:
            debut.append(n)
            break
John
  • 1,837
  • 1
  • 8
  • 12
  • Really, I didn't know the for loops automatically increment n and m! thats good to know. And I go through all columns for each line. So iterating columns before lines. Correct me if I am wrong Thanks – Mat17 Feb 21 '19 at 18:55
  • If you want to do all columns for each line (so all columns for line 0 then all columns for line 1 and so on) you need to have your loop over columns inside your loop over lines. – John Feb 21 '19 at 19:10
  • Ok, I see what you're saying, my only worry is for the resent of n, does it do it automatically when going out of the second for loop? Thanks – Mat17 Feb 21 '19 at 19:23
  • And do you have an easy method for finding the most comment value in 'debut'? I have been trying value_count and does not seem to work with a list, only with a dataframe – Mat17 Feb 21 '19 at 19:29
  • It will automatically go to the next value of m when it exits the inner loop and moves to the next iteration of the outer loop and will automatically restart n at 0 when it restarts the inner loop on the next iteration of the outer loop. I'm not sure what you mean by "most comment value of debut." Do you mean the most value that occurs most frequently? If so, have a look at: https://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list – John Feb 21 '19 at 20:51