pandas.DataFrame.truncate

DataFrame.truncate(before=Noneafter=Noneaxis=Nonecopy=True)[source]

Truncates a sorted DataFrame/Series before and/or after some particular index value. If the axis contains only datetime values, before/after parameters are converted to datetime values.

Parameters:

before : date, string, int

Truncate all rows before this index value

after : date, string, int

Truncate all rows after this index value

axis : {0 or ‘index’, 1 or ‘columns’}

  • 0 or ‘index’: apply truncation to rows
  • 1 or ‘columns’: apply truncation to columns

Default is stat axis for given data type (0 for Series and DataFrames, 1 for Panels)

copy : boolean, default is True,

return a copy of the truncated section

Returns:

truncated : type of caller

Examples

>>> df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'],
...                    'B': ['f', 'g', 'h', 'i', 'j'],
...                    'C': ['k', 'l', 'm', 'n', 'o']},
...                    index=[1, 2, 3, 4, 5])
>>> df.truncate(before=2, after=4)
   A  B  C
2  b  g  l
3  c  h  m
4  d  i  n
>>> df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
...                    'B': [6, 7, 8, 9, 10],
...                    'C': [11, 12, 13, 14, 15]},
...                    index=['a', 'b', 'c', 'd', 'e'])
>>> df.truncate(before='b', after='d')
   A  B   C
b  2  7  12
c  3  8  13
d  4  9  14

The index values in truncate can be datetimes or string dates. Note that truncate assumes a 0 value for any unspecified date component in a DatetimeIndex in contrast to slicing which returns any partially matching dates.

>>> dates = pd.date_range('2016-01-01', '2016-02-01', freq='s')
>>> df = pd.DataFrame(index=dates, data={'A': 1})
>>> df.truncate('2016-01-05', '2016-01-10').tail()
                     A
2016-01-09 23:59:56  1
2016-01-09 23:59:57  1
2016-01-09 23:59:58  1
2016-01-09 23:59:59  1
2016-01-10 00:00:00  1
>>> df.loc['2016-01-05':'2016-01-10', :].tail()
                     A
2016-01-10 23:59:55  1
2016-01-10 23:59:56  1
2016-01-10 23:59:57  1
2016-01-10 23:59:58  1
2016-01-10 23:59:59  1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值