📜  Python| Pandas TimedeltaIndex.get_level_values(1)

📅  最后修改于: 2023-12-03 15:34:16.503000             🧑  作者: Mango

Python | Pandas TimedeltaIndex.get_level_values

Pandas is an open source Python package that is most widely used for data science/data analysis and machine learning tasks. It is built on top of another package named Numpy, which provides support for multi-dimensional arrays.

Pandas TimedeltaIndex.get_level_values method is used to get values of the levels of the TimedeltaIndex.

Syntax: TimedeltaIndex.get_level_values(level)

Parameters: level: int or str integer or string value to get values from the index level.

Return type: ndarray

Let's look at an example:

import pandas as pd
import numpy as np

tdi = pd.DataFrame({'A': np.array([pd.Timedelta('1 days'), pd.Timedelta('2 days'), pd.Timedelta('3 days'), pd.Timedelta('4 days')])})

tdi.index = pd.TimedeltaIndex([pd.Timedelta(days=i) for i in range(4)])

print(tdi.index.get_level_values(0))

Output:

TimedeltaIndex(['0 days', '1 days', '2 days', '3 days'], dtype='timedelta64[ns]', freq=None)

In the above example, we have created a TimedeltaIndex using a list comprehension that stores Timedelta values of increasing numbers of days. By using the get_level_values method, we get the values of the TimedeltaIndex at level 0.

We can also pass the name of the level instead of the integer value to the get_level_values method:

print(tdi.index.get_level_values('days'))

Output:

TimedeltaIndex(['0 days', '1 days', '2 days', '3 days'], dtype='timedelta64[ns]', freq=None)

In the above example, we have passed the name of the level 'days' to the get_level_values method and get the same output as before.

We can use this method to get specific values from the TimedeltaIndex based on levels.