thinwybk
thinwybk

Reputation: 4753

How can I define a single pandas Interval?

For unit testing I need a single interval. However usually one uses interval_range(), from_arrays(), from_tuples(), from_breaks() to construct a new IntervalIndex containing several intervals. How can I get a single interval index?

Upvotes: 1

Views: 252

Answers (3)

root
root

Reputation: 33783

You can create a single scalar Interval object by specifying left, right and optionally closed:

In [1]: import pandas as pd; pd.__version__
Out[1]: '0.25.3'

In [2]: iv = pd.Interval(0, 1, closed='neither')

In [3]: iv
Out[3]: Interval(0, 1, closed='neither')

You can create an IntervalIndex from a list of scalar Interval objects:

In [4]: ii = pd.IntervalIndex([iv])

In [5]: ii
Out[5]: 
IntervalIndex([(0, 1)],
              closed='neither',
              dtype='interval[int64]')

In [6]: pd.IntervalIndex([iv, 2*iv, 3*iv])
Out[6]: 
IntervalIndex([(0, 1), (0, 2), (0, 3)],
              closed='neither',
              dtype='interval[int64]')


Upvotes: 1

ignoring_gravity
ignoring_gravity

Reputation: 10476

If I've understood the question, this should work:

import pandas as pd

pd.interval_range(start=0, end=5, periods=1)

This returns a single interval:

IntervalIndex([(0, 5]],
              closed='right',
              dtype='interval[int64]')

Upvotes: 1

Daniele Cappuccio
Daniele Cappuccio

Reputation: 2192

According to pandas docs, you can specify a periods=1 parameter in interval_range to create an IntervalIndex object with a single interval.

Upvotes: -1

Related Questions