个性化阅读
专注于IT技术分析

Python Pandas Series.truncate()用法介绍

熊猫系列是带有轴标签的一维ndarray。标签不必是唯一的, 但必须是可哈希的类型。该对象同时支持基于整数和基于标签的索引, 并提供了许多用于执行涉及索引的操作的方法。

大熊猫Series.truncate()函数用于在某个索引值之前和之后截断Series或DataFrame。这是基于高于或低于某些阈值的索引值进行布尔索引的有用捷径。

语法:Series.truncate(before = None, after = None, axis = None, copy = True)
参数:
before:截断此索引值之前的所有行。
after:截断此索引值之后的所有行。
axis:要截断的轴。默认情况下截断索引(行)。
copy:返回截断部分的副本。
返回:截断的Series或DataFrame。

示例1:采用Series.truncate()函数可在给定日期之前截断该系列中的某些数据。

# 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)

输出:

Python Pandas Series.truncate()1

现在我们将使用Series.truncate()函数可截断给定Series对象中” 2014-08-17 10:00:00 + 02:00″之前的数据。

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

输出:

Python Pandas Series.truncate()2

正如我们在输出中看到的, Series.truncate()函数已成功截断了上述日期之前的所有数据。

示例2:采用Series.truncate()函数在给定索引标签之前和之后, 截断序列中的某些数据。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([ 19.5 , 16.8 , 22.78 , 20.124 , 18.1002 ])
  
# Print the series
print (sr)

输出:

Python Pandas Series.truncate()3

现在我们将使用Series.truncate()函数可截断给定Series对象中第一个索引标签之前和第三个索引标签之后的数据。

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

输出:

Python Pandas Series.truncate()4

正如我们在输出中看到的, Series.truncate()函数已成功截断了上述索引标签之前和之后的所有数据。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python Pandas Series.truncate()用法介绍

评论 抢沙发

评论前必须登录!