+

Python | Pandas TimedeltaIndex.factorize

TimedeltaIndex.factorize() Pandas TimedeltaIndex.factorize() encodes the elements of a given TimedeltaIndex as an enumerated type or categorical variable.

Syntax: TimedeltaIndex.factorize (sort = False, na_sentinel = -1)

Parameters:
sort: Sort by values ​​
na_sentinel: Value to mark “not found”

Return : labels: the indexer to the original array

Example # 1: Use TimedeltaIndex.factorize () to encode elements of the specified TimedeltaIndex objects.

# import pandas as pd

import pandas as pd

  # Create TimedeltaIndex object

tidx = pd.TimedeltaIndex (start = `1 days 06: 05: 01.000030` ,

periods = 5 , freq = `D` , name = ` Koala` )

 
# Print the TimedeltaIndex object

print (tidx)

Output:

We will now use TimedeltaIndex.factorize () to encode the tidx object.

# encode tidx object
tidx.factorize ()

Output:

As we can see in the output, TimedeltaIndex.factorize () encoded the elements of the tidx object. He assigned a unique code to each element.

Example # 2: Use TimedeltaIndex.factorize () to check if the elements contained in two given objects TimedeltaIndex, the same or not.

# import pandas as pd

import pandas as pd

 
# Create TimedeltaIndex object

tidx = pd .TimedeltaIndex (data = [ `1 days 02:00:00 ` , ` 1 days 06: 05: 01.000030` ,

` 1 days 02: 00: 00` , `1 days 02: 00: 00` , `21 days 06: 15: 01.000030` ])

 
# Print the TimedeltaIndex object

print (tidx)

Output:

Now we will use TimedeltaIndex.factorize () to encode the tidx object.

# encode tidx object
tidx.factorize ()

Output:

As we can see in the output, TimedeltaIndex.factorize () encoded the elements of the tidx object. He assigned a unique code to each element.

Get Solution for free from DataCamp guru