Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Return a dataframe of the components of the TimedeltaIndex
The TimedeltaIndex.components property in Pandas returns a DataFrame containing the individual components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of each timedelta in the index.
Creating a TimedeltaIndex
First, let's create a TimedeltaIndex with various time durations ?
import pandas as pd
# Create a TimedeltaIndex with different time formats
tdIndex = pd.TimedeltaIndex(data=['10 day 5h 2 min 35s 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])
print("TimedeltaIndex:")
print(tdIndex)
TimedeltaIndex:
TimedeltaIndex(['10 days 05:02:35.000003010', '0 days 22:39:19.999999',
'2 days 07:08:02.000045', '0 days 21:15:45.999999'],
dtype='timedelta64[ns]', freq=None)
Accessing Individual Properties
You can access individual time components using specific properties ?
import pandas as pd
tdIndex = pd.TimedeltaIndex(data=['10 day 5h 2 min 35s 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])
# Individual components
print("Days:", tdIndex.days)
print("Seconds:", tdIndex.seconds)
print("Microseconds:", tdIndex.microseconds)
Days: Int64Index([10, 0, 2, 0], dtype='int64') Seconds: Int64Index([18155, 81559, 25682, 76545], dtype='int64') Microseconds: Int64Index([3, 999999, 45, 999999], dtype='int64')
Using the components Property
The components property returns a DataFrame with all time components organized in columns ?
import pandas as pd
tdIndex = pd.TimedeltaIndex(data=['10 day 5h 2 min 35s 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])
# Get all components as a DataFrame
components_df = tdIndex.components
print("Components DataFrame:")
print(components_df)
Components DataFrame: days hours minutes seconds milliseconds microseconds nanoseconds 0 10 5 2 35 0 3 10 1 0 22 39 19 999 999 0 2 2 7 8 2 0 45 0 3 0 21 15 45 999 999 0
Key Features
| Component | Description | Range |
|---|---|---|
| days | Number of days | Any integer |
| hours | Hours component | 0-23 |
| minutes | Minutes component | 0-59 |
| seconds | Seconds component | 0-59 |
| milliseconds | Milliseconds component | 0-999 |
| microseconds | Microseconds component | 0-999 |
| nanoseconds | Nanoseconds component | 0-999 |
Conclusion
The components property provides a convenient way to break down TimedeltaIndex into individual time units. This is useful for analyzing time duration data and performing component-wise operations on timedelta objects.
Advertisements
