Home > Back-end >  Iterating through a series using an if loop to sort data into different buckets
Iterating through a series using an if loop to sort data into different buckets

Time:11-13

I currently have a dataframe with one column in it:

import pandas as pd

data = {'Time': [55.760, 140.685, 53.543, 53.521, 219.675, 54.095, 58.000, 134.258, 52.860, 54.852, 147.068, 49.160, 53.244]
            }

c = pd.DataFrame(data)

index   Time
0      55.760
2      140.685
4      53.543
6      53.521
8      219.675
10     54.094
12     58.000
14     134.257
16     52.860
18     54.852
20     147.067
22     49.160
24     53.244

if c in range(0,25):
    ex = .2
elif c in range(25,60):
    ex = .4
else:
    ex = .6

I need to look at each value and if its from 0 < 25, ex =.2 and so on like in the if loop. The ex value is then used to run in an equation afterwards that varies. With how this is set up now I receive an error saying:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I am not too sure at this point what to change.

CodePudding user response:

Use np.select instead of the if statements:

np.select([c < 25, (c >= 25) & (c < 60), c >= 60], [.2, .4, .6])
  • Related