dimanche 18 juillet 2021

Replace item in a list based on index

I have a dataframe that contains 3 columns (A, B, C).

  • A is a number from 0 to n (equal to the row index), which I need to generate for the equipment that will read the file with the dataframe and use it.

  • B is a column that has either a value of 100 or another value below it.

  • C is a column with positional values, let's say 0, 0.5, 1, 1.5 and so on.

The goal is to make a fourth column D that is filled either with 1's or 2's depending on the row. For example, let's say that every 3, 4 or 5 rows it will put a 2, depending on a variable called size = 0.5 that works with column C. Below you can find an example of how the dataframe could look like in the D column.

Example of df: | A | B | C | D | |---|---|---|---| | 0 | 100 | 0 | 1 | | 1 | 100 | 0 | 2 | | 2 | 1 | 0 | 1 | | 3 | 1 | 0 | 1 | | 4 | 1 | 0 | 1 | | 5 | 1 | 0 | 2 | | 6 | 1 | 0 | 1 | | 7 | 1 | 0 | 1 | | 8 | 1 | 0 | 1 | | 9 | 1 | 0 | 2 | | 10 | 1 | 0 | 1 | | 11 | 1 | 0 | 1 | | 12 | 1 | 0 | 1 | | 13 | 1 | 0 | 2 | | 14 | 100 | 0.5 | 1 | | 15 | 100 | 0.5 | 2 | | 16 | 1 | 0.5 | 1 | | 17 | 1 | 0.5 | 1 | | 18 | 1 | 0.5 | 2 | | 19 | 1 | 0.5 | 1 | | 20 | 1 | 0.5 | 1 | | 21 | 1 | 0.5 | 1 | | 22 | 1 | 0.5 | 2 | | 23 | 1 | 0.5 | 1 | | 24 | 1 | 0.5 | 1 | | 25 | 1 | 0.5 | 1 | | 26 | 1 | 0.5 | 2 | | 27 | 1 | 0.5 | 1 |

Some of the code that I am using can be found below.

for num in df.A:
            if ((df.A[num] % 2 == 0) and (df.B[num] == 100)):
                D.append(1)    

            elif ((df.A[num] % 2 != 0) and (df.B[num] == 100)):
                D.append(2)

            elif df.B[num] != 100:
                D.append(1)            

                ##### ------ This code doesn't work as expected
                if size < df.C[num] <= 2 * size:
                    for row in range(len(df)):
                        if row % 5 == 0:
                            D[num] = 2      

                # Code to complete the next step which will be similar to the previous
                elif 2 * size < df.C[num] <= 3 * size:
                    pass

The part mark ##### ------ This code doesn't work as expected outputs only 2's instead of having 1's and only 2's for the selected rows. I guess that using a condition based on % may not be the best way to do it, since I want the 2's to be equispaced. However, I could not think of better way to do it.

Any ideas on how to approach this? Thank you very much.

Aucun commentaire:

Enregistrer un commentaire