Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/pandas/core/indexes/timedeltas.py: 38%

62 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1""" implement the TimedeltaIndex """ 

2from __future__ import annotations 

3 

4from pandas._libs import ( 

5 index as libindex, 

6 lib, 

7) 

8from pandas._libs.tslibs import ( 

9 Timedelta, 

10 to_offset, 

11) 

12from pandas._typing import DtypeObj 

13 

14from pandas.core.dtypes.common import ( 

15 TD64NS_DTYPE, 

16 is_scalar, 

17 is_timedelta64_dtype, 

18) 

19 

20from pandas.core.arrays import datetimelike as dtl 

21from pandas.core.arrays.timedeltas import TimedeltaArray 

22import pandas.core.common as com 

23from pandas.core.indexes.base import ( 

24 Index, 

25 maybe_extract_name, 

26) 

27from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin 

28from pandas.core.indexes.extension import inherit_names 

29 

30 

31@inherit_names( 

32 ["__neg__", "__pos__", "__abs__", "total_seconds", "round", "floor", "ceil"] 

33 + TimedeltaArray._field_ops, 

34 TimedeltaArray, 

35 wrap=True, 

36) 

37@inherit_names( 

38 [ 

39 "components", 

40 "to_pytimedelta", 

41 "sum", 

42 "std", 

43 "median", 

44 "_format_native_types", 

45 ], 

46 TimedeltaArray, 

47) 

48class TimedeltaIndex(DatetimeTimedeltaMixin): 

49 """ 

50 Immutable Index of timedelta64 data. 

51 

52 Represented internally as int64, and scalars returned Timedelta objects. 

53 

54 Parameters 

55 ---------- 

56 data : array-like (1-dimensional), optional 

57 Optional timedelta-like data to construct index with. 

58 unit : unit of the arg (D,h,m,s,ms,us,ns) denote the unit, optional 

59 Which is an integer/float number. 

60 freq : str or pandas offset object, optional 

61 One of pandas date offset strings or corresponding objects. The string 

62 'infer' can be passed in order to set the frequency of the index as the 

63 inferred frequency upon creation. 

64 copy : bool 

65 Make a copy of input ndarray. 

66 name : object 

67 Name to be stored in the index. 

68 

69 Attributes 

70 ---------- 

71 days 

72 seconds 

73 microseconds 

74 nanoseconds 

75 components 

76 inferred_freq 

77 

78 Methods 

79 ------- 

80 to_pytimedelta 

81 to_series 

82 round 

83 floor 

84 ceil 

85 to_frame 

86 mean 

87 

88 See Also 

89 -------- 

90 Index : The base pandas Index type. 

91 Timedelta : Represents a duration between two dates or times. 

92 DatetimeIndex : Index of datetime64 data. 

93 PeriodIndex : Index of Period data. 

94 timedelta_range : Create a fixed-frequency TimedeltaIndex. 

95 

96 Notes 

97 ----- 

98 To learn more about the frequency strings, please see `this link 

99 <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__. 

100 """ 

101 

102 _typ = "timedeltaindex" 

103 

104 _data_cls = TimedeltaArray 

105 

106 @property 

107 def _engine_type(self) -> type[libindex.TimedeltaEngine]: 

108 return libindex.TimedeltaEngine 

109 

110 _data: TimedeltaArray 

111 

112 # Use base class method instead of DatetimeTimedeltaMixin._get_string_slice 

113 _get_string_slice = Index._get_string_slice 

114 

115 # ------------------------------------------------------------------- 

116 # Constructors 

117 

118 def __new__( 

119 cls, 

120 data=None, 

121 unit=None, 

122 freq=lib.no_default, 

123 closed=None, 

124 dtype=TD64NS_DTYPE, 

125 copy=False, 

126 name=None, 

127 ): 

128 name = maybe_extract_name(name, data, cls) 

129 

130 if is_scalar(data): 

131 raise cls._scalar_data_error(data) 

132 

133 if unit in {"Y", "y", "M"}: 

134 raise ValueError( 

135 "Units 'M', 'Y', and 'y' are no longer supported, as they do not " 

136 "represent unambiguous timedelta values durations." 

137 ) 

138 

139 # FIXME: need to check for dtype/data match 

140 if isinstance(data, TimedeltaArray) and freq is lib.no_default: 

141 if copy: 

142 data = data.copy() 

143 return cls._simple_new(data, name=name) 

144 

145 if isinstance(data, TimedeltaIndex) and freq is lib.no_default and name is None: 

146 if copy: 

147 return data.copy() 

148 else: 

149 return data._view() 

150 

151 # - Cases checked above all return/raise before reaching here - # 

152 

153 tdarr = TimedeltaArray._from_sequence_not_strict( 

154 data, freq=freq, unit=unit, dtype=dtype, copy=copy 

155 ) 

156 return cls._simple_new(tdarr, name=name) 

157 

158 # ------------------------------------------------------------------- 

159 

160 def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: 

161 """ 

162 Can we compare values of the given dtype to our own? 

163 """ 

164 return is_timedelta64_dtype(dtype) # aka self._data._is_recognized_dtype 

165 

166 # ------------------------------------------------------------------- 

167 # Indexing Methods 

168 

169 def get_loc(self, key, method=None, tolerance=None): 

170 """ 

171 Get integer location for requested label 

172 

173 Returns 

174 ------- 

175 loc : int, slice, or ndarray[int] 

176 """ 

177 self._check_indexing_error(key) 

178 

179 try: 

180 key = self._data._validate_scalar(key, unbox=False) 

181 except TypeError as err: 

182 raise KeyError(key) from err 

183 

184 return Index.get_loc(self, key, method, tolerance) 

185 

186 def _parse_with_reso(self, label: str): 

187 # the "with_reso" is a no-op for TimedeltaIndex 

188 parsed = Timedelta(label) 

189 return parsed, None 

190 

191 def _parsed_string_to_bounds(self, reso, parsed: Timedelta): 

192 # reso is unused, included to match signature of DTI/PI 

193 lbound = parsed.round(parsed.resolution_string) 

194 rbound = lbound + to_offset(parsed.resolution_string) - Timedelta(1, "ns") 

195 return lbound, rbound 

196 

197 # ------------------------------------------------------------------- 

198 

199 @property 

200 def inferred_type(self) -> str: 

201 return "timedelta64" 

202 

203 

204def timedelta_range( 

205 start=None, 

206 end=None, 

207 periods: int | None = None, 

208 freq=None, 

209 name=None, 

210 closed=None, 

211) -> TimedeltaIndex: 

212 """ 

213 Return a fixed frequency TimedeltaIndex with day as the default. 

214 

215 Parameters 

216 ---------- 

217 start : str or timedelta-like, default None 

218 Left bound for generating timedeltas. 

219 end : str or timedelta-like, default None 

220 Right bound for generating timedeltas. 

221 periods : int, default None 

222 Number of periods to generate. 

223 freq : str or DateOffset, default 'D' 

224 Frequency strings can have multiples, e.g. '5H'. 

225 name : str, default None 

226 Name of the resulting TimedeltaIndex. 

227 closed : str, default None 

228 Make the interval closed with respect to the given frequency to 

229 the 'left', 'right', or both sides (None). 

230 

231 Returns 

232 ------- 

233 TimedeltaIndex 

234 

235 Notes 

236 ----- 

237 Of the four parameters ``start``, ``end``, ``periods``, and ``freq``, 

238 exactly three must be specified. If ``freq`` is omitted, the resulting 

239 ``TimedeltaIndex`` will have ``periods`` linearly spaced elements between 

240 ``start`` and ``end`` (closed on both sides). 

241 

242 To learn more about the frequency strings, please see `this link 

243 <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__. 

244 

245 Examples 

246 -------- 

247 >>> pd.timedelta_range(start='1 day', periods=4) 

248 TimedeltaIndex(['1 days', '2 days', '3 days', '4 days'], 

249 dtype='timedelta64[ns]', freq='D') 

250 

251 The ``closed`` parameter specifies which endpoint is included. The default 

252 behavior is to include both endpoints. 

253 

254 >>> pd.timedelta_range(start='1 day', periods=4, closed='right') 

255 TimedeltaIndex(['2 days', '3 days', '4 days'], 

256 dtype='timedelta64[ns]', freq='D') 

257 

258 The ``freq`` parameter specifies the frequency of the TimedeltaIndex. 

259 Only fixed frequencies can be passed, non-fixed frequencies such as 

260 'M' (month end) will raise. 

261 

262 >>> pd.timedelta_range(start='1 day', end='2 days', freq='6H') 

263 TimedeltaIndex(['1 days 00:00:00', '1 days 06:00:00', '1 days 12:00:00', 

264 '1 days 18:00:00', '2 days 00:00:00'], 

265 dtype='timedelta64[ns]', freq='6H') 

266 

267 Specify ``start``, ``end``, and ``periods``; the frequency is generated 

268 automatically (linearly spaced). 

269 

270 >>> pd.timedelta_range(start='1 day', end='5 days', periods=4) 

271 TimedeltaIndex(['1 days 00:00:00', '2 days 08:00:00', '3 days 16:00:00', 

272 '5 days 00:00:00'], 

273 dtype='timedelta64[ns]', freq=None) 

274 """ 

275 if freq is None and com.any_none(periods, start, end): 

276 freq = "D" 

277 

278 freq, _ = dtl.maybe_infer_freq(freq) 

279 tdarr = TimedeltaArray._generate_range(start, end, periods, freq, closed=closed) 

280 return TimedeltaIndex._simple_new(tdarr, name=name)