Python | Панды Series.truncate ()

Опубликовано: 28 Марта, 2022

Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.

Pandas Series.truncate() function is used to truncate a Series or DataFrame before and after some index value. This is a useful shorthand for boolean indexing based on index values above or below certain thresholds.

Syntax: Series.truncate(before=None, after=None, axis=None, copy=True)

Parameter :
before : Truncate all rows before this index value.
after : Truncate all rows after this index value.
axis : Axis to truncate. Truncates the index (rows) by default.
copy : Return a copy of the truncated section.

Returns : truncated Series or DataFrame.

Example #1: Use Series.truncate() function to truncate some data from the series prior to a given date.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(["New York", "Chicago", "Toronto", "Lisbon", "Rio", "Moscow"])
  
# Create the Datetime Index
didx = pd.DatetimeIndex(start ="2014-08-01 10:00", freq ="W"
                     periods = 6, tz = "Europe/Berlin"
  
# set the index
sr.index = didx
  
# Print the series
print(sr)

Выход :

Now we will use Series.truncate() function to truncate data which are prior to ‘2014-08-17 10:00:00+02:00’ in the given Series object.

# truncate data prior to the given date
sr.truncate(before = "2014-08-17 10:00:00 + 02:00")

Выход :

As we can see in the output, the Series.truncate() function has successfully truncated all data prior to the mentioned date.

Example #2: Use Series.truncate() function to truncate some data from the series prior to a given index label and after a given index label.

Выход :

Now we will use Series.truncate() function to truncate data which are prior to the 1st index label and after the 3rd index label in the given Series object.

# truncate data outside the given range
sr.truncate(before = 1, after = 3)

Выход :

As we can see in the output, the Series.truncate() function has successfully truncated all data prior to the mentioned index label and after the mentioned index label.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.