Pandas to_timedelta(~)
方法將給定參數轉換為 timedelta。 Timedeltas 是用於執行日期算術的時間單位(例如 1 小時 40 毫秒)。
參數
1.arg
| string
或 timedelta
或 array-like
要轉換為時間增量的數據。
2. unit
| string
| optional
提供的 arg
的單位。直接取自官方文檔的可能值如下:
'Y', 'M', 'W', 'D', 'days', 'day', 'hours', 'hour', 'hr', 'h',
'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds', 'sec', 'second',
'ms', 'milliseconds', 'millisecond', 'milli', 'millis', 'L',
'us', 'microseconds', 'microsecond', 'micro', 'micros', 'U',
'ns', 'nanoseconds', 'nano', 'nanos', 'nanosecond', 'N'
默認情況下,unit="ns"
(納秒)。
3. errors
| string
| optional
當arg
無法轉換為時間增量時如何處理:
值 |
說明 |
---|---|
|
如果無法解析 |
|
如果無法解析,則返回 |
|
如果無法解析 |
默認情況下,errors="raise"
。
返回值
如果提供單個數據單元,則返回timedelta64
。否則,返回 timedelta64
的 NumPy 數組。
例子
來自字符串
要將字符串轉換為時間增量:
pd.to_timedelta("2 days 03:04:05")
Timedelta('2 days 03:04:05')
從一組數字
要將數字數組轉換為 timedelta
數組:
pd.to_timedelta([20,15], unit="hours")
TimedeltaIndex(['20:00:00', '15:00:00'], dtype='timedelta64[ns]', freq=None)
注意
小數點也將被考慮在內。例如,考慮以下情況:
pd.to_timedelta([2.5], unit="D")
TimedeltaIndex(['2 days 12:00:00'], dtype='timedelta64[ns]', freq=None)
我們看到2.5
天被解釋為2
天和12
小時。
處理錯誤
增加
默認情況下,errors="raise"
- 如果任何轉換不成功,則會引發錯誤。例如,假設我們有一些無意義的數據,如下所示:
pd.to_timedelta([20,[]], unit="hours") # errors="raise"
ValueError: Invalid type for timedelta scalar: <class 'list'>
忽視
每當從特定值的轉換不成功時,我們可以使該方法返回該值而不是拋出錯誤。這是通過設置 unit="ignore"
來完成的:
pd.to_timedelta([20,[]], unit="hours", errors="ignore")
array([20, list([])], dtype=object)
強製
對於不成功的轉換,我們可以讓該方法返回 NaT
(not-a-time):
pd.to_timedelta([20,[]], unit="hours", errors="coerce")
TimedeltaIndex(['20:00:00', NaT], dtype='timedelta64[ns]', freq=None)
timedelta 的實際使用
Timedelta
主要用於執行日期運算。例如,您可以對 DatetimeIndex
中的日期應用 2 天的偏移量,如下所示:
idx = pd.DatetimeIndex(["2020-12-25","2020-12-26"])
idx + pd.to_timedelta("2D")
DatetimeIndex(['2020-12-27', '2020-12-28'], dtype='datetime64[ns]', freq=None)
我們還可以將 Timedelta
添加到日期列中。例如,考慮以下情況:
df = pd.DataFrame({"A": pd.date_range("2020-12-25", "2020-12-26")})
df
A
0 2020-12-25
1 2020-12-26
讓我們在這些日期中添加幾天:
df["B"] = df["A"] + pd.to_timedelta([3.5, 4], unit="D")
df
A B
0 2020-12-25 2020-12-28 12:00:00
1 2020-12-26 2020-12-30 00:00:00
在這裏,生成的列 B
也是 datetime
:
df.dtypes
A datetime64[ns]
B datetime64[ns]
dtype: object
相關用法
- Python Pandas to_datetime方法用法及代碼示例
- Python Pandas to_numeric方法用法及代碼示例
- Python torch.distributed.rpc.rpc_async用法及代碼示例
- Python torch.nn.InstanceNorm3d用法及代碼示例
- Python torchaudio.transforms.Fade用法及代碼示例
- Python torch.special.gammaincc用法及代碼示例
- Python torch.optim.lr_scheduler.ConstantLR用法及代碼示例
- Python torch.normal用法及代碼示例
- Python torchdata.datapipes.iter.Multiplexer用法及代碼示例
- Python torch.nn.quantized.dynamic.LSTM用法及代碼示例
- Python torch.nn.EmbeddingBag用法及代碼示例
- Python torch.nn.Module.register_forward_hook用法及代碼示例
- Python torch.nn.AvgPool2d用法及代碼示例
- Python torch.nn.PixelShuffle用法及代碼示例
- Python torch.Generator.initial_seed用法及代碼示例
- Python torch.resolve_neg用法及代碼示例
- Python torchtext.vocab.Vectors.get_vecs_by_tokens用法及代碼示例
- Python torch.nn.CELU用法及代碼示例
- Python torch.reciprocal用法及代碼示例
- Python torch.nn.Hardsigmoid用法及代碼示例
- Python torch.fft.fft用法及代碼示例
- Python torch.distributed.TCPStore用法及代碼示例
- Python torch.distributed.pipeline.sync.skip.skippable.stash用法及代碼示例
- Python torch.nn.GLU用法及代碼示例
- Python torch.nn.functional.conv1d用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas | to_timedelta method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。