dumbledad
dumbledad

Reputation: 17527

Create pandas series of intervals from pandas series of values

The closest answer I can find seems too complex: How I can create an interval column in pandas?

If I had a pandas data frame that looked like this:

+-------+
| Value |
+-------+
|     6 |
|    12 |
|    56 |
|    60 |
|   120 |
+-------+

How might I turn it into this?

+-------+-----------+
| Value | Interval  |
+-------+-----------+
|     6 |           |
|    12 | (6, 12]   |
|    56 | (12, 56]  |
|    60 | (56, 60]  |
|   120 | (60, 120] |
+-------+-----------+

(N.B. This is a very simplified example, my real data-frame is big and so performance is an issue.)

Upvotes: 3

Views: 592

Answers (1)

ALollz
ALollz

Reputation: 59519

pd.cut defaults to right=True so if 'Value' is strictly monotonically increasing

df['Interval'] = pd.cut(df.Value, bins=df.Value)
#   Value       Interval
#0      6            NaN
#1     12    (6.0, 12.0]
#2     56   (12.0, 56.0]
#3     60   (56.0, 60.0]
#4    120  (60.0, 120.0]

Upvotes: 3

Related Questions