Python酷库之旅-第三方库Pandas(025)

目录

一、用法精讲

63、pandas.to_timedelta函数

63-1、语法

63-2、参数

63-3、功能

63-4、返回值

63-5、说明

63-6、用法

63-6-1、数据准备

63-6-2、代码示例

63-6-3、结果输出

64、pandas.date_range函数

64-1、语法

64-2、参数

64-3、功能

64-4、返回值

64-5、说明

64-6、用法

64-6-1、数据准备

64-6-2、代码示例

64-6-3、结果输出 

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

63、pandas.to_timedelta函数
63-1、语法
# 63、pandas.to_timedelta函数
pandas.to_timedelta(arg, unit=None, errors='raise')
Convert argument to timedelta.

Timedeltas are absolute differences in times, expressed in difference units (e.g. days, hours, minutes, seconds). This method converts an argument from a recognized timedelta format / value into a Timedelta type.

Parameters:
argstr, timedelta, list-like or Series
The data to be converted to timedelta.

Changed in version 2.0: Strings with units ‘M’, ‘Y’ and ‘y’ do not represent unambiguous timedelta values and will raise an exception.

unitstr, optional
Denotes the unit of the arg for numeric arg. Defaults to "ns".

Possible values:

‘W’

‘D’ / ‘days’ / ‘day’

‘hours’ / ‘hour’ / ‘hr’ / ‘h’ / ‘H’

‘m’ / ‘minute’ / ‘min’ / ‘minutes’ / ‘T’

‘s’ / ‘seconds’ / ‘sec’ / ‘second’ / ‘S’

‘ms’ / ‘milliseconds’ / ‘millisecond’ / ‘milli’ / ‘millis’ / ‘L’

‘us’ / ‘microseconds’ / ‘microsecond’ / ‘micro’ / ‘micros’ / ‘U’

‘ns’ / ‘nanoseconds’ / ‘nano’ / ‘nanos’ / ‘nanosecond’ / ‘N’

Must not be specified when arg contains strings and errors="raise".

Deprecated since version 2.2.0: Units ‘H’, ‘T’, ‘S’, ‘L’, ‘U’ and ‘N’ are deprecated and will be removed in a future version. Please use ‘h’, ‘min’, ‘s’, ‘ms’, ‘us’, and ‘ns’ instead of ‘H’, ‘T’, ‘S’, ‘L’, ‘U’ and ‘N’.

errors{‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’
If ‘raise’, then invalid parsing will raise an exception.

If ‘coerce’, then invalid parsing will be set as NaT.

If ‘ignore’, then invalid parsing will return the input.

Returns:
timedelta
If parsing succeeded. Return type depends on input:

list-like: TimedeltaIndex of timedelta64 dtype

Series: Series of timedelta64 dtype

scalar: Timedelta
63-2、参数

63-2-1、arg(必须)该参数可以是以下几种形式之一:

  • 数值(整数或浮点数),表示时间量。
  • 字符串或字符串列表,表示时间量。
  • pandas.Series或pandas.DataFrame,包含时间差值的数据。

63-2-2、unit(可选,默认值为None)用于指定arg中数值的单位,如果arg是数值类型,则unit必须指定为以下值之一:

  • 'Y'或'y':
  • 'M':
  • 'W':
  • 'D'或'd':
  • 'h':小时
  • 'm':分钟
  • 's':
  • 'ms':毫秒
  • 'us':微秒
  • 'ns':纳秒

63-2-3、errors(可选,默认值为'raise')指定当arg不能被解析为时间差值时的错误处理方式,可选值包括:

  • 'raise':当解析失败时会抛出错误。
  • 'coerce':当解析失败时,会返回NaT(表示缺失的时间差值)。
  • 'ignore':当解析失败时,会返回原始输入的arg。
63-3、功能

        用于将不同格式的时间差值(如字符串、数值等)转换为Timedelta类型的函数,该函数可以处理多种输入格式,包括字符串、整数、浮点数以及包含这些类型的序列或DataFrame列。 

63-4、返回值

        返回一个Timedelta对象、TimedeltaIndexSeries,具体取决于输入数据的类型:

63-4-1、如果输入的是单个值,则返回Timedelta对象;

63-4-2、如果输入的是列表或数组,则返回TimedeltaIndex

63-4-3、如果输入的是pandas Series则返回Series

63-5、说明

        无

63-6、用法
63-6-1、数据准备
63-6-2、代码示例
# 63、pandas.to_timedelta函数
# 63-1、单个字符串
import pandas as pd
single_timedelta = pd.to_timedelta('2 days 3 hours 45 minutes')
print(single_timedelta, end='\n\n')

# 63-2、列表
import pandas as pd
list_timedelta = pd.to_timedelta(['1 days', '2 days 03:04:05.123456', '15.5us'])
print(list_timedelta, end='\n\n')

# 63-3、数字表示天数
import pandas as pd
numeric_timedelta = pd.to_timedelta([1, 2, 3], unit='D')
print(numeric_timedelta, end='\n\n')

# 63-4、错误处理
import pandas as pd
error_timedelta = pd.to_timedelta(['1 days', 'not_a_time', '2 days'], errors='coerce')
print(error_timedelta)
63-6-3、结果输出
# 63、pandas.to_timedelta函数
# 63-1、单个字符串
# 2 days 03:45:00

# 63-2、列表
# TimedeltaIndex(['1 days 00:00:00', '2 days 03:04:05.123456',
#                 '0 days 00:00:00.000015500'],
#                dtype='timedelta64[ns]', freq=None)

# 63-3、数字表示天数
# TimedeltaIndex(['1 days', '2 days', '3 days'], dtype='timedelta64[ns]', freq=None)

# 63-4、错误处理
# TimedeltaIndex(['1 days', NaT, '2 days'], dtype='timedelta64[ns]', freq=None)
64、pandas.date_range函数
64-1、语法
# 64、pandas.date_range函数
pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, inclusive='both', *, unit=None, **kwargs)
Return a fixed frequency DatetimeIndex.

Returns the range of equally spaced time points (where the difference between any two adjacent points is specified by the given frequency) such that they all satisfy start <[=] x <[=] end, where the first one and the last one are, resp., the first and last time points in that range that fall on the boundary of freq (if given as a frequency string) or that are valid for freq (if given as a pandas.tseries.offsets.DateOffset). (If exactly one of start, end, or freq is not specified, this missing parameter can be computed given periods, the number of timesteps in the range. See the note below.)

Parameters:
startstr or datetime-like, optional
Left bound for generating dates.

endstr or datetime-like, optional
Right bound for generating dates.

periodsint, optional
Number of periods to generate.

freqstr, Timedelta, datetime.timedelta, or DateOffset, default ‘D’
Frequency strings can have multiples, e.g. ‘5h’. See here for a list of frequency aliases.

tzstr or tzinfo, optional
Time zone name for returning localized DatetimeIndex, for example ‘Asia/Hong_Kong’. By default, the resulting DatetimeIndex is timezone-naive unless timezone-aware datetime-likes are passed.

normalizebool, default False
Normalize start/end dates to midnight before generating date range.

namestr, default None
Name of the resulting DatetimeIndex.

inclusive{“both”, “neither”, “left”, “right”}, default “both”
Include boundaries; Whether to set each bound as closed or open.

New in version 1.4.0.

unitstr, default None
Specify the desired resolution of the result.

New in version 2.0.0.

**kwargs
For compatibility. Has no effect on the result.

Returns:
DatetimeIndex
64-2、参数

64-2-1、start(可选,默认值为None)字符串或datetime-like,时间范围的起始点。

64-2-2、end(可选,默认值为None)字符串或datetime-like,时间范围的结束点,如果指定了periods,则这个参数是可选的。

64-2-3、periods(可选,默认值为None)整数,要生成的周期数,如果指定了periods,则不需要end(或start,尽管这通常不太有用)。

64-2-4、freq(可选,默认值为None)字符串或DateOffset对象,表示频率。例如,'D'表示日频率,'H'表示小时频率,如果不指定,则必须同时指定periods和start/end。

64-2-5、tz(可选,默认值为None)字符串或tzinfo对象,指定时区。

64-2-6、normalize(可选,默认值为False)布尔值,如果为True,则将开始和结束时间规范化到午夜。

64-2-7、name(可选,默认值为None)字符串,可选的名称,用于返回的DatetimeIndex。

64-2-8、inclusive(可选,默认值为'both')包括或排除起始和结束点,可以是 'both'、'neither'、'left'或'right'。

64-2-9、unit(可选,默认值为None)在较新版本的Pandas中,这个参数已经被弃用,并且不应在新代码中使用。它曾用于与start, end和periods参数一起指定时间单位的,但现在这些参数应该直接接受datetime-like对象或相应的字符串表示。

64-2-10、**kwargs(可选)其他关键字参数,这些参数可能会传递给Timedelta或to_timedelta,但在大多数情况下,你不需要直接使用它们。

64-3、功能

        用于生成固定频率日期时间索引的函数。

64-4、返回值

        返回一个包含指定日期时间范围的Pandas DatetimeIndex对象。

64-5、说明

        无

64-6、用法
64-6-1、数据准备
64-6-2、代码示例
# 64、pandas.date_range函数
# 64-1、指定开始时间和结束时间,生成默认频率(天)的日期范围
import pandas as pd
date_range_1 = pd.date_range(start='2024-01-01', end='2024-12-31')
print(date_range_1, end='\n\n')

# 64-2:指定开始时间和时间点数,生成默认频率(天)的日期范围
import pandas as pd
date_range_2 = pd.date_range(start='2024-01-01', periods=10)
print(date_range_2, end='\n\n')

# 64-3:指定开始时间和结束时间,生成每小时的日期范围
import pandas as pd
date_range_3 = pd.date_range(start='2024-01-01', end='2024-12-31', freq='H')
print(date_range_3, end='\n\n')

# 64-4:指定开始时间和结束时间,生成特定频率的日期范围(每月)
import pandas as pd
date_range_4 = pd.date_range(start='2024-01-01', end='2024-06-01', freq='M')
print(date_range_4, end='\n\n')

# 64-5:指定时区
import pandas as pd
date_range_5 = pd.date_range(start='2024-01-01', periods=10, freq='D', tz='UTC')
print(date_range_5, end='\n\n')

# 64-6:标准化时间戳
import pandas as pd
date_range_6 = pd.date_range(start='2024-01-01 15:00:00', periods=10, normalize=True)
print(date_range_6, end='\n\n')

# 64-7:包含或排除结束点
import pandas as pd
date_range_7 = pd.date_range(start='2024-01-01', end='2024-12-31', inclusive='neither')
print(date_range_7, end='\n\n')

# 64-8:指定名称
import pandas as pd
date_range_8 = pd.date_range(start='2024-01-01', end='2024-12-31', name='my_date_range')
print(date_range_8)
64-6-3、结果输出 
# 64、pandas.date_range函数
# 64-1、指定开始时间和结束时间,生成默认频率(天)的日期范围
# DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04',
#                '2024-01-05', '2024-01-06', '2024-01-07', '2024-01-08',
#                '2024-01-09', '2024-01-10',
#                ...
#                '2024-12-22', '2024-12-23', '2024-12-24', '2024-12-25',
#                '2024-12-26', '2024-12-27', '2024-12-28', '2024-12-29',
#                '2024-12-30', '2024-12-31'],
#               dtype='datetime64[ns]', length=366, freq='D')

# 64-2、指定开始时间和时间点数,生成默认频率(天)的日期范围
# DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04',
#                '2024-01-05', '2024-01-06', '2024-01-07', '2024-01-08',
#                '2024-01-09', '2024-01-10'],
#               dtype='datetime64[ns]', freq='D')

# 64-3、指定开始时间和结束时间,生成每小时的日期范围
# DatetimeIndex(['2024-01-01 00:00:00', '2024-01-01 01:00:00',
#                '2024-01-01 02:00:00', '2024-01-01 03:00:00',
#                '2024-01-01 04:00:00', '2024-01-01 05:00:00',
#                '2024-01-01 06:00:00', '2024-01-01 07:00:00',
#                '2024-01-01 08:00:00', '2024-01-01 09:00:00',
#                ...
#                '2024-12-30 15:00:00', '2024-12-30 16:00:00',
#                '2024-12-30 17:00:00', '2024-12-30 18:00:00',
#                '2024-12-30 19:00:00', '2024-12-30 20:00:00',
#                '2024-12-30 21:00:00', '2024-12-30 22:00:00',
#                '2024-12-30 23:00:00', '2024-12-31 00:00:00'],
#               dtype='datetime64[ns]', length=8761, freq='h')

# 64-4、指定开始时间和结束时间,生成特定频率的日期范围(每月)
# DatetimeIndex(['2024-01-31', '2024-02-29', '2024-03-31', '2024-04-30',
#                '2024-05-31'],
#               dtype='datetime64[ns]', freq='ME')

# 64-5、指定时区
# DatetimeIndex(['2024-01-01 00:00:00+00:00', '2024-01-02 00:00:00+00:00',
#                '2024-01-03 00:00:00+00:00', '2024-01-04 00:00:00+00:00',
#                '2024-01-05 00:00:00+00:00', '2024-01-06 00:00:00+00:00',
#                '2024-01-07 00:00:00+00:00', '2024-01-08 00:00:00+00:00',
#                '2024-01-09 00:00:00+00:00', '2024-01-10 00:00:00+00:00'],
#               dtype='datetime64[ns, UTC]', freq='D')

# 64-6、标准化时间戳
# DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04',
#                '2024-01-05', '2024-01-06', '2024-01-07', '2024-01-08',
#                '2024-01-09', '2024-01-10'],
#               dtype='datetime64[ns]', freq='D')

# 64-7、包含或排除结束点
# DatetimeIndex(['2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05',
#                '2024-01-06', '2024-01-07', '2024-01-08', '2024-01-09',
#                '2024-01-10', '2024-01-11',
#                ...
#                '2024-12-21', '2024-12-22', '2024-12-23', '2024-12-24',
#                '2024-12-25', '2024-12-26', '2024-12-27', '2024-12-28',
#                '2024-12-29', '2024-12-30'],
#               dtype='datetime64[ns]', length=364, freq='D')

# 64-8、指定名称
# DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04',
#                '2024-01-05', '2024-01-06', '2024-01-07', '2024-01-08',
#                '2024-01-09', '2024-01-10',
#                ...
#                '2024-12-22', '2024-12-23', '2024-12-24', '2024-12-25',
#                '2024-12-26', '2024-12-27', '2024-12-28', '2024-12-29',
#                '2024-12-30', '2024-12-31'],
#               dtype='datetime64[ns]', name='my_date_range', length=366, freq='D')

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页
  • 27
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神奇夜光杯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值