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
Python Pandas - Extract the Number of microseconds for each element from TimeDeltaIndex
To extract the number of microseconds for each element from TimeDeltaIndex object, use the TimedeltaIndex.microseconds property. This property returns an Int64Index containing the microsecond component of each timedelta.
Creating a TimeDeltaIndex
First, let's create a TimeDeltaIndex object with various timedelta formats ?
import pandas as pd
# Create a TimeDeltaIndex object with different timedelta 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)
Extracting Microseconds
Use the microseconds property to extract only the microsecond component from each timedelta ?
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'])
# Extract microseconds from each element
microseconds = tdIndex.microseconds
print("Microseconds from TimeDeltaIndex:")
print(microseconds)
print(f"Type: {type(microseconds)}")
Microseconds from TimeDeltaIndex: Int64Index([3, 999999, 45, 999999], dtype='int64') Type: <class 'pandas.core.indexes.numeric.Int64Index'>
Understanding the Components
To better understand how microseconds fit into the overall timedelta structure, we can view all components ?
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'])
# Display all components including microseconds
components_df = tdIndex.components
print("Complete breakdown of TimeDelta components:")
print(components_df)
# Focus on microseconds column
print(f"\nMicroseconds only: {components_df['microseconds'].tolist()}")
Complete breakdown of TimeDelta components: 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 Microseconds only: [3, 999999, 45, 999999]
Key Points
| Property | Returns | Range |
|---|---|---|
microseconds |
Int64Index | 0 to 999999 |
components |
DataFrame | All time components |
Conclusion
The TimedeltaIndex.microseconds property efficiently extracts just the microsecond component from each timedelta element. Use components property for a complete breakdown of all time units including days, hours, minutes, seconds, milliseconds, microseconds, and nanoseconds.
