base_parser.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. from __future__ import annotations
  2. from collections import defaultdict
  3. from copy import copy
  4. import csv
  5. import datetime
  6. from enum import Enum
  7. import itertools
  8. from typing import (
  9. TYPE_CHECKING,
  10. Any,
  11. Callable,
  12. Hashable,
  13. Iterable,
  14. List,
  15. Mapping,
  16. Sequence,
  17. Tuple,
  18. cast,
  19. final,
  20. overload,
  21. )
  22. import warnings
  23. import numpy as np
  24. from pandas._libs import (
  25. lib,
  26. parsers,
  27. )
  28. import pandas._libs.ops as libops
  29. from pandas._libs.parsers import STR_NA_VALUES
  30. from pandas._libs.tslibs import parsing
  31. from pandas._typing import (
  32. ArrayLike,
  33. DtypeArg,
  34. DtypeObj,
  35. Scalar,
  36. )
  37. from pandas.compat._optional import import_optional_dependency
  38. from pandas.errors import (
  39. ParserError,
  40. ParserWarning,
  41. )
  42. from pandas.util._exceptions import find_stack_level
  43. from pandas.core.dtypes.astype import astype_array
  44. from pandas.core.dtypes.common import (
  45. ensure_object,
  46. is_bool_dtype,
  47. is_dict_like,
  48. is_dtype_equal,
  49. is_extension_array_dtype,
  50. is_float_dtype,
  51. is_integer,
  52. is_integer_dtype,
  53. is_list_like,
  54. is_object_dtype,
  55. is_scalar,
  56. is_string_dtype,
  57. pandas_dtype,
  58. )
  59. from pandas.core.dtypes.dtypes import (
  60. CategoricalDtype,
  61. ExtensionDtype,
  62. )
  63. from pandas.core.dtypes.missing import isna
  64. from pandas import (
  65. ArrowDtype,
  66. DatetimeIndex,
  67. StringDtype,
  68. )
  69. from pandas.core import algorithms
  70. from pandas.core.arrays import (
  71. ArrowExtensionArray,
  72. BooleanArray,
  73. Categorical,
  74. ExtensionArray,
  75. FloatingArray,
  76. IntegerArray,
  77. )
  78. from pandas.core.arrays.boolean import BooleanDtype
  79. from pandas.core.indexes.api import (
  80. Index,
  81. MultiIndex,
  82. default_index,
  83. ensure_index_from_sequences,
  84. )
  85. from pandas.core.series import Series
  86. from pandas.core.tools import datetimes as tools
  87. from pandas.io.common import is_potential_multi_index
  88. if TYPE_CHECKING:
  89. from pandas import DataFrame
  90. class ParserBase:
  91. class BadLineHandleMethod(Enum):
  92. ERROR = 0
  93. WARN = 1
  94. SKIP = 2
  95. _implicit_index: bool = False
  96. _first_chunk: bool
  97. def __init__(self, kwds) -> None:
  98. self.names = kwds.get("names")
  99. self.orig_names: Sequence[Hashable] | None = None
  100. self.index_col = kwds.get("index_col", None)
  101. self.unnamed_cols: set = set()
  102. self.index_names: Sequence[Hashable] | None = None
  103. self.col_names: Sequence[Hashable] | None = None
  104. self.parse_dates = _validate_parse_dates_arg(kwds.pop("parse_dates", False))
  105. self._parse_date_cols: Iterable = []
  106. self.date_parser = kwds.pop("date_parser", lib.no_default)
  107. self.date_format = kwds.pop("date_format", None)
  108. self.dayfirst = kwds.pop("dayfirst", False)
  109. self.keep_date_col = kwds.pop("keep_date_col", False)
  110. self.na_values = kwds.get("na_values")
  111. self.na_fvalues = kwds.get("na_fvalues")
  112. self.na_filter = kwds.get("na_filter", False)
  113. self.keep_default_na = kwds.get("keep_default_na", True)
  114. self.dtype = copy(kwds.get("dtype", None))
  115. self.converters = kwds.get("converters")
  116. self.dtype_backend = kwds.get("dtype_backend")
  117. self.true_values = kwds.get("true_values")
  118. self.false_values = kwds.get("false_values")
  119. self.cache_dates = kwds.pop("cache_dates", True)
  120. self._date_conv = _make_date_converter(
  121. date_parser=self.date_parser,
  122. date_format=self.date_format,
  123. dayfirst=self.dayfirst,
  124. cache_dates=self.cache_dates,
  125. )
  126. # validate header options for mi
  127. self.header = kwds.get("header")
  128. if is_list_like(self.header, allow_sets=False):
  129. if kwds.get("usecols"):
  130. raise ValueError(
  131. "cannot specify usecols when specifying a multi-index header"
  132. )
  133. if kwds.get("names"):
  134. raise ValueError(
  135. "cannot specify names when specifying a multi-index header"
  136. )
  137. # validate index_col that only contains integers
  138. if self.index_col is not None:
  139. if not (
  140. is_list_like(self.index_col, allow_sets=False)
  141. and all(map(is_integer, self.index_col))
  142. or is_integer(self.index_col)
  143. ):
  144. raise ValueError(
  145. "index_col must only contain row numbers "
  146. "when specifying a multi-index header"
  147. )
  148. self._name_processed = False
  149. self._first_chunk = True
  150. self.usecols, self.usecols_dtype = self._validate_usecols_arg(kwds["usecols"])
  151. # Fallback to error to pass a sketchy test(test_override_set_noconvert_columns)
  152. # Normally, this arg would get pre-processed earlier on
  153. self.on_bad_lines = kwds.get("on_bad_lines", self.BadLineHandleMethod.ERROR)
  154. def _validate_parse_dates_presence(self, columns: Sequence[Hashable]) -> Iterable:
  155. """
  156. Check if parse_dates are in columns.
  157. If user has provided names for parse_dates, check if those columns
  158. are available.
  159. Parameters
  160. ----------
  161. columns : list
  162. List of names of the dataframe.
  163. Returns
  164. -------
  165. The names of the columns which will get parsed later if a dict or list
  166. is given as specification.
  167. Raises
  168. ------
  169. ValueError
  170. If column to parse_date is not in dataframe.
  171. """
  172. cols_needed: Iterable
  173. if is_dict_like(self.parse_dates):
  174. cols_needed = itertools.chain(*self.parse_dates.values())
  175. elif is_list_like(self.parse_dates):
  176. # a column in parse_dates could be represented
  177. # ColReference = Union[int, str]
  178. # DateGroups = List[ColReference]
  179. # ParseDates = Union[DateGroups, List[DateGroups],
  180. # Dict[ColReference, DateGroups]]
  181. cols_needed = itertools.chain.from_iterable(
  182. col if is_list_like(col) and not isinstance(col, tuple) else [col]
  183. for col in self.parse_dates
  184. )
  185. else:
  186. cols_needed = []
  187. cols_needed = list(cols_needed)
  188. # get only columns that are references using names (str), not by index
  189. missing_cols = ", ".join(
  190. sorted(
  191. {
  192. col
  193. for col in cols_needed
  194. if isinstance(col, str) and col not in columns
  195. }
  196. )
  197. )
  198. if missing_cols:
  199. raise ValueError(
  200. f"Missing column provided to 'parse_dates': '{missing_cols}'"
  201. )
  202. # Convert positions to actual column names
  203. return [
  204. col if (isinstance(col, str) or col in columns) else columns[col]
  205. for col in cols_needed
  206. ]
  207. def close(self) -> None:
  208. pass
  209. @final
  210. @property
  211. def _has_complex_date_col(self) -> bool:
  212. return isinstance(self.parse_dates, dict) or (
  213. isinstance(self.parse_dates, list)
  214. and len(self.parse_dates) > 0
  215. and isinstance(self.parse_dates[0], list)
  216. )
  217. @final
  218. def _should_parse_dates(self, i: int) -> bool:
  219. if isinstance(self.parse_dates, bool):
  220. return self.parse_dates
  221. else:
  222. if self.index_names is not None:
  223. name = self.index_names[i]
  224. else:
  225. name = None
  226. j = i if self.index_col is None else self.index_col[i]
  227. if is_scalar(self.parse_dates):
  228. return (j == self.parse_dates) or (
  229. name is not None and name == self.parse_dates
  230. )
  231. else:
  232. return (j in self.parse_dates) or (
  233. name is not None and name in self.parse_dates
  234. )
  235. @final
  236. def _extract_multi_indexer_columns(
  237. self,
  238. header,
  239. index_names: Sequence[Hashable] | None,
  240. passed_names: bool = False,
  241. ) -> tuple[
  242. Sequence[Hashable], Sequence[Hashable] | None, Sequence[Hashable] | None, bool
  243. ]:
  244. """
  245. Extract and return the names, index_names, col_names if the column
  246. names are a MultiIndex.
  247. Parameters
  248. ----------
  249. header: list of lists
  250. The header rows
  251. index_names: list, optional
  252. The names of the future index
  253. passed_names: bool, default False
  254. A flag specifying if names where passed
  255. """
  256. if len(header) < 2:
  257. return header[0], index_names, None, passed_names
  258. # the names are the tuples of the header that are not the index cols
  259. # 0 is the name of the index, assuming index_col is a list of column
  260. # numbers
  261. ic = self.index_col
  262. if ic is None:
  263. ic = []
  264. if not isinstance(ic, (list, tuple, np.ndarray)):
  265. ic = [ic]
  266. sic = set(ic)
  267. # clean the index_names
  268. index_names = header.pop(-1)
  269. index_names, _, _ = self._clean_index_names(index_names, self.index_col)
  270. # extract the columns
  271. field_count = len(header[0])
  272. # check if header lengths are equal
  273. if not all(len(header_iter) == field_count for header_iter in header[1:]):
  274. raise ParserError("Header rows must have an equal number of columns.")
  275. def extract(r):
  276. return tuple(r[i] for i in range(field_count) if i not in sic)
  277. columns = list(zip(*(extract(r) for r in header)))
  278. names = columns.copy()
  279. for single_ic in sorted(ic):
  280. names.insert(single_ic, single_ic)
  281. # Clean the column names (if we have an index_col).
  282. if len(ic):
  283. col_names = [
  284. r[ic[0]]
  285. if ((r[ic[0]] is not None) and r[ic[0]] not in self.unnamed_cols)
  286. else None
  287. for r in header
  288. ]
  289. else:
  290. col_names = [None] * len(header)
  291. passed_names = True
  292. return names, index_names, col_names, passed_names
  293. @final
  294. def _maybe_make_multi_index_columns(
  295. self,
  296. columns: Sequence[Hashable],
  297. col_names: Sequence[Hashable] | None = None,
  298. ) -> Sequence[Hashable] | MultiIndex:
  299. # possibly create a column mi here
  300. if is_potential_multi_index(columns):
  301. list_columns = cast(List[Tuple], columns)
  302. return MultiIndex.from_tuples(list_columns, names=col_names)
  303. return columns
  304. @final
  305. def _make_index(
  306. self, data, alldata, columns, indexnamerow: list[Scalar] | None = None
  307. ) -> tuple[Index | None, Sequence[Hashable] | MultiIndex]:
  308. index: Index | None
  309. if not is_index_col(self.index_col) or not self.index_col:
  310. index = None
  311. elif not self._has_complex_date_col:
  312. simple_index = self._get_simple_index(alldata, columns)
  313. index = self._agg_index(simple_index)
  314. elif self._has_complex_date_col:
  315. if not self._name_processed:
  316. (self.index_names, _, self.index_col) = self._clean_index_names(
  317. list(columns), self.index_col
  318. )
  319. self._name_processed = True
  320. date_index = self._get_complex_date_index(data, columns)
  321. index = self._agg_index(date_index, try_parse_dates=False)
  322. # add names for the index
  323. if indexnamerow:
  324. coffset = len(indexnamerow) - len(columns)
  325. assert index is not None
  326. index = index.set_names(indexnamerow[:coffset])
  327. # maybe create a mi on the columns
  328. columns = self._maybe_make_multi_index_columns(columns, self.col_names)
  329. return index, columns
  330. @final
  331. def _get_simple_index(self, data, columns):
  332. def ix(col):
  333. if not isinstance(col, str):
  334. return col
  335. raise ValueError(f"Index {col} invalid")
  336. to_remove = []
  337. index = []
  338. for idx in self.index_col:
  339. i = ix(idx)
  340. to_remove.append(i)
  341. index.append(data[i])
  342. # remove index items from content and columns, don't pop in
  343. # loop
  344. for i in sorted(to_remove, reverse=True):
  345. data.pop(i)
  346. if not self._implicit_index:
  347. columns.pop(i)
  348. return index
  349. @final
  350. def _get_complex_date_index(self, data, col_names):
  351. def _get_name(icol):
  352. if isinstance(icol, str):
  353. return icol
  354. if col_names is None:
  355. raise ValueError(f"Must supply column order to use {icol!s} as index")
  356. for i, c in enumerate(col_names):
  357. if i == icol:
  358. return c
  359. to_remove = []
  360. index = []
  361. for idx in self.index_col:
  362. name = _get_name(idx)
  363. to_remove.append(name)
  364. index.append(data[name])
  365. # remove index items from content and columns, don't pop in
  366. # loop
  367. for c in sorted(to_remove, reverse=True):
  368. data.pop(c)
  369. col_names.remove(c)
  370. return index
  371. def _clean_mapping(self, mapping):
  372. """converts col numbers to names"""
  373. if not isinstance(mapping, dict):
  374. return mapping
  375. clean = {}
  376. # for mypy
  377. assert self.orig_names is not None
  378. for col, v in mapping.items():
  379. if isinstance(col, int) and col not in self.orig_names:
  380. col = self.orig_names[col]
  381. clean[col] = v
  382. if isinstance(mapping, defaultdict):
  383. remaining_cols = set(self.orig_names) - set(clean.keys())
  384. clean.update({col: mapping[col] for col in remaining_cols})
  385. return clean
  386. @final
  387. def _agg_index(self, index, try_parse_dates: bool = True) -> Index:
  388. arrays = []
  389. converters = self._clean_mapping(self.converters)
  390. for i, arr in enumerate(index):
  391. if try_parse_dates and self._should_parse_dates(i):
  392. arr = self._date_conv(
  393. arr,
  394. col=self.index_names[i] if self.index_names is not None else None,
  395. )
  396. if self.na_filter:
  397. col_na_values = self.na_values
  398. col_na_fvalues = self.na_fvalues
  399. else:
  400. col_na_values = set()
  401. col_na_fvalues = set()
  402. if isinstance(self.na_values, dict):
  403. assert self.index_names is not None
  404. col_name = self.index_names[i]
  405. if col_name is not None:
  406. col_na_values, col_na_fvalues = _get_na_values(
  407. col_name, self.na_values, self.na_fvalues, self.keep_default_na
  408. )
  409. clean_dtypes = self._clean_mapping(self.dtype)
  410. cast_type = None
  411. index_converter = False
  412. if self.index_names is not None:
  413. if isinstance(clean_dtypes, dict):
  414. cast_type = clean_dtypes.get(self.index_names[i], None)
  415. if isinstance(converters, dict):
  416. index_converter = converters.get(self.index_names[i]) is not None
  417. try_num_bool = not (
  418. cast_type and is_string_dtype(cast_type) or index_converter
  419. )
  420. arr, _ = self._infer_types(
  421. arr, col_na_values | col_na_fvalues, cast_type is None, try_num_bool
  422. )
  423. arrays.append(arr)
  424. names = self.index_names
  425. index = ensure_index_from_sequences(arrays, names)
  426. return index
  427. @final
  428. def _convert_to_ndarrays(
  429. self,
  430. dct: Mapping,
  431. na_values,
  432. na_fvalues,
  433. verbose: bool = False,
  434. converters=None,
  435. dtypes=None,
  436. ):
  437. result = {}
  438. for c, values in dct.items():
  439. conv_f = None if converters is None else converters.get(c, None)
  440. if isinstance(dtypes, dict):
  441. cast_type = dtypes.get(c, None)
  442. else:
  443. # single dtype or None
  444. cast_type = dtypes
  445. if self.na_filter:
  446. col_na_values, col_na_fvalues = _get_na_values(
  447. c, na_values, na_fvalues, self.keep_default_na
  448. )
  449. else:
  450. col_na_values, col_na_fvalues = set(), set()
  451. if c in self._parse_date_cols:
  452. # GH#26203 Do not convert columns which get converted to dates
  453. # but replace nans to ensure to_datetime works
  454. mask = algorithms.isin(values, set(col_na_values) | col_na_fvalues)
  455. np.putmask(values, mask, np.nan)
  456. result[c] = values
  457. continue
  458. if conv_f is not None:
  459. # conv_f applied to data before inference
  460. if cast_type is not None:
  461. warnings.warn(
  462. (
  463. "Both a converter and dtype were specified "
  464. f"for column {c} - only the converter will be used."
  465. ),
  466. ParserWarning,
  467. stacklevel=find_stack_level(),
  468. )
  469. try:
  470. values = lib.map_infer(values, conv_f)
  471. except ValueError:
  472. # error: Argument 2 to "isin" has incompatible type "List[Any]";
  473. # expected "Union[Union[ExtensionArray, ndarray], Index, Series]"
  474. mask = algorithms.isin(
  475. values, list(na_values) # type: ignore[arg-type]
  476. ).view(np.uint8)
  477. values = lib.map_infer_mask(values, conv_f, mask)
  478. cvals, na_count = self._infer_types(
  479. values,
  480. set(col_na_values) | col_na_fvalues,
  481. cast_type is None,
  482. try_num_bool=False,
  483. )
  484. else:
  485. is_ea = is_extension_array_dtype(cast_type)
  486. is_str_or_ea_dtype = is_ea or is_string_dtype(cast_type)
  487. # skip inference if specified dtype is object
  488. # or casting to an EA
  489. try_num_bool = not (cast_type and is_str_or_ea_dtype)
  490. # general type inference and conversion
  491. cvals, na_count = self._infer_types(
  492. values,
  493. set(col_na_values) | col_na_fvalues,
  494. cast_type is None,
  495. try_num_bool,
  496. )
  497. # type specified in dtype param or cast_type is an EA
  498. if cast_type and (not is_dtype_equal(cvals, cast_type) or is_ea):
  499. if not is_ea and na_count > 0:
  500. if is_bool_dtype(cast_type):
  501. raise ValueError(f"Bool column has NA values in column {c}")
  502. cast_type = pandas_dtype(cast_type)
  503. cvals = self._cast_types(cvals, cast_type, c)
  504. result[c] = cvals
  505. if verbose and na_count:
  506. print(f"Filled {na_count} NA values in column {c!s}")
  507. return result
  508. @final
  509. def _set_noconvert_dtype_columns(
  510. self, col_indices: list[int], names: Sequence[Hashable]
  511. ) -> set[int]:
  512. """
  513. Set the columns that should not undergo dtype conversions.
  514. Currently, any column that is involved with date parsing will not
  515. undergo such conversions. If usecols is specified, the positions of the columns
  516. not to cast is relative to the usecols not to all columns.
  517. Parameters
  518. ----------
  519. col_indices: The indices specifying order and positions of the columns
  520. names: The column names which order is corresponding with the order
  521. of col_indices
  522. Returns
  523. -------
  524. A set of integers containing the positions of the columns not to convert.
  525. """
  526. usecols: list[int] | list[str] | None
  527. noconvert_columns = set()
  528. if self.usecols_dtype == "integer":
  529. # A set of integers will be converted to a list in
  530. # the correct order every single time.
  531. usecols = sorted(self.usecols)
  532. elif callable(self.usecols) or self.usecols_dtype not in ("empty", None):
  533. # The names attribute should have the correct columns
  534. # in the proper order for indexing with parse_dates.
  535. usecols = col_indices
  536. else:
  537. # Usecols is empty.
  538. usecols = None
  539. def _set(x) -> int:
  540. if usecols is not None and is_integer(x):
  541. x = usecols[x]
  542. if not is_integer(x):
  543. x = col_indices[names.index(x)]
  544. return x
  545. if isinstance(self.parse_dates, list):
  546. for val in self.parse_dates:
  547. if isinstance(val, list):
  548. for k in val:
  549. noconvert_columns.add(_set(k))
  550. else:
  551. noconvert_columns.add(_set(val))
  552. elif isinstance(self.parse_dates, dict):
  553. for val in self.parse_dates.values():
  554. if isinstance(val, list):
  555. for k in val:
  556. noconvert_columns.add(_set(k))
  557. else:
  558. noconvert_columns.add(_set(val))
  559. elif self.parse_dates:
  560. if isinstance(self.index_col, list):
  561. for k in self.index_col:
  562. noconvert_columns.add(_set(k))
  563. elif self.index_col is not None:
  564. noconvert_columns.add(_set(self.index_col))
  565. return noconvert_columns
  566. def _infer_types(
  567. self, values, na_values, no_dtype_specified, try_num_bool: bool = True
  568. ) -> tuple[ArrayLike, int]:
  569. """
  570. Infer types of values, possibly casting
  571. Parameters
  572. ----------
  573. values : ndarray
  574. na_values : set
  575. no_dtype_specified: Specifies if we want to cast explicitly
  576. try_num_bool : bool, default try
  577. try to cast values to numeric (first preference) or boolean
  578. Returns
  579. -------
  580. converted : ndarray or ExtensionArray
  581. na_count : int
  582. """
  583. na_count = 0
  584. if issubclass(values.dtype.type, (np.number, np.bool_)):
  585. # If our array has numeric dtype, we don't have to check for strings in isin
  586. na_values = np.array([val for val in na_values if not isinstance(val, str)])
  587. mask = algorithms.isin(values, na_values)
  588. na_count = mask.astype("uint8", copy=False).sum()
  589. if na_count > 0:
  590. if is_integer_dtype(values):
  591. values = values.astype(np.float64)
  592. np.putmask(values, mask, np.nan)
  593. return values, na_count
  594. dtype_backend = self.dtype_backend
  595. non_default_dtype_backend = (
  596. no_dtype_specified and dtype_backend is not lib.no_default
  597. )
  598. result: ArrayLike
  599. if try_num_bool and is_object_dtype(values.dtype):
  600. # exclude e.g DatetimeIndex here
  601. try:
  602. result, result_mask = lib.maybe_convert_numeric(
  603. values,
  604. na_values,
  605. False,
  606. convert_to_masked_nullable=non_default_dtype_backend, # type: ignore[arg-type] # noqa
  607. )
  608. except (ValueError, TypeError):
  609. # e.g. encountering datetime string gets ValueError
  610. # TypeError can be raised in floatify
  611. na_count = parsers.sanitize_objects(values, na_values)
  612. result = values
  613. else:
  614. if non_default_dtype_backend:
  615. if result_mask is None:
  616. result_mask = np.zeros(result.shape, dtype=np.bool_)
  617. if result_mask.all():
  618. result = IntegerArray(
  619. np.ones(result_mask.shape, dtype=np.int64), result_mask
  620. )
  621. elif is_integer_dtype(result):
  622. result = IntegerArray(result, result_mask)
  623. elif is_bool_dtype(result):
  624. result = BooleanArray(result, result_mask)
  625. elif is_float_dtype(result):
  626. result = FloatingArray(result, result_mask)
  627. na_count = result_mask.sum()
  628. else:
  629. na_count = isna(result).sum()
  630. else:
  631. result = values
  632. if values.dtype == np.object_:
  633. na_count = parsers.sanitize_objects(values, na_values)
  634. if result.dtype == np.object_ and try_num_bool:
  635. result, bool_mask = libops.maybe_convert_bool(
  636. np.asarray(values),
  637. true_values=self.true_values,
  638. false_values=self.false_values,
  639. convert_to_masked_nullable=non_default_dtype_backend, # type: ignore[arg-type] # noqa
  640. )
  641. if result.dtype == np.bool_ and non_default_dtype_backend:
  642. if bool_mask is None:
  643. bool_mask = np.zeros(result.shape, dtype=np.bool_)
  644. result = BooleanArray(result, bool_mask)
  645. elif result.dtype == np.object_ and non_default_dtype_backend:
  646. # read_excel sends array of datetime objects
  647. inferred_type = lib.infer_dtype(result)
  648. if inferred_type != "datetime":
  649. result = StringDtype().construct_array_type()._from_sequence(values)
  650. if dtype_backend == "pyarrow":
  651. pa = import_optional_dependency("pyarrow")
  652. if isinstance(result, np.ndarray):
  653. result = ArrowExtensionArray(pa.array(result, from_pandas=True))
  654. else:
  655. # ExtensionArray
  656. result = ArrowExtensionArray(
  657. pa.array(result.to_numpy(), from_pandas=True)
  658. )
  659. return result, na_count
  660. def _cast_types(self, values: ArrayLike, cast_type: DtypeObj, column) -> ArrayLike:
  661. """
  662. Cast values to specified type
  663. Parameters
  664. ----------
  665. values : ndarray or ExtensionArray
  666. cast_type : np.dtype or ExtensionDtype
  667. dtype to cast values to
  668. column : string
  669. column name - used only for error reporting
  670. Returns
  671. -------
  672. converted : ndarray or ExtensionArray
  673. """
  674. if isinstance(cast_type, CategoricalDtype):
  675. known_cats = cast_type.categories is not None
  676. if not is_object_dtype(values.dtype) and not known_cats:
  677. # TODO: this is for consistency with
  678. # c-parser which parses all categories
  679. # as strings
  680. values = lib.ensure_string_array(
  681. values, skipna=False, convert_na_value=False
  682. )
  683. cats = Index(values).unique().dropna()
  684. values = Categorical._from_inferred_categories(
  685. cats, cats.get_indexer(values), cast_type, true_values=self.true_values
  686. )
  687. # use the EA's implementation of casting
  688. elif isinstance(cast_type, ExtensionDtype):
  689. array_type = cast_type.construct_array_type()
  690. try:
  691. if isinstance(cast_type, BooleanDtype):
  692. # error: Unexpected keyword argument "true_values" for
  693. # "_from_sequence_of_strings" of "ExtensionArray"
  694. return array_type._from_sequence_of_strings( # type: ignore[call-arg] # noqa:E501
  695. values,
  696. dtype=cast_type,
  697. true_values=self.true_values,
  698. false_values=self.false_values,
  699. )
  700. else:
  701. return array_type._from_sequence_of_strings(values, dtype=cast_type)
  702. except NotImplementedError as err:
  703. raise NotImplementedError(
  704. f"Extension Array: {array_type} must implement "
  705. "_from_sequence_of_strings in order to be used in parser methods"
  706. ) from err
  707. elif isinstance(values, ExtensionArray):
  708. values = values.astype(cast_type, copy=False)
  709. elif issubclass(cast_type.type, str):
  710. # TODO: why skipna=True here and False above? some tests depend
  711. # on it here, but nothing fails if we change it above
  712. # (as no tests get there as of 2022-12-06)
  713. values = lib.ensure_string_array(
  714. values, skipna=True, convert_na_value=False
  715. )
  716. else:
  717. try:
  718. values = astype_array(values, cast_type, copy=True)
  719. except ValueError as err:
  720. raise ValueError(
  721. f"Unable to convert column {column} to type {cast_type}"
  722. ) from err
  723. return values
  724. @overload
  725. def _do_date_conversions(
  726. self,
  727. names: Index,
  728. data: DataFrame,
  729. ) -> tuple[Sequence[Hashable] | Index, DataFrame]:
  730. ...
  731. @overload
  732. def _do_date_conversions(
  733. self,
  734. names: Sequence[Hashable],
  735. data: Mapping[Hashable, ArrayLike],
  736. ) -> tuple[Sequence[Hashable], Mapping[Hashable, ArrayLike]]:
  737. ...
  738. def _do_date_conversions(
  739. self,
  740. names: Sequence[Hashable] | Index,
  741. data: Mapping[Hashable, ArrayLike] | DataFrame,
  742. ) -> tuple[Sequence[Hashable] | Index, Mapping[Hashable, ArrayLike] | DataFrame]:
  743. # returns data, columns
  744. if self.parse_dates is not None:
  745. data, names = _process_date_conversion(
  746. data,
  747. self._date_conv,
  748. self.parse_dates,
  749. self.index_col,
  750. self.index_names,
  751. names,
  752. keep_date_col=self.keep_date_col,
  753. dtype_backend=self.dtype_backend,
  754. )
  755. return names, data
  756. def _check_data_length(
  757. self,
  758. columns: Sequence[Hashable],
  759. data: Sequence[ArrayLike],
  760. ) -> None:
  761. """Checks if length of data is equal to length of column names.
  762. One set of trailing commas is allowed. self.index_col not False
  763. results in a ParserError previously when lengths do not match.
  764. Parameters
  765. ----------
  766. columns: list of column names
  767. data: list of array-likes containing the data column-wise.
  768. """
  769. if not self.index_col and len(columns) != len(data) and columns:
  770. empty_str = is_object_dtype(data[-1]) and data[-1] == ""
  771. # error: No overload variant of "__ror__" of "ndarray" matches
  772. # argument type "ExtensionArray"
  773. empty_str_or_na = empty_str | isna(data[-1]) # type: ignore[operator]
  774. if len(columns) == len(data) - 1 and np.all(empty_str_or_na):
  775. return
  776. warnings.warn(
  777. "Length of header or names does not match length of data. This leads "
  778. "to a loss of data with index_col=False.",
  779. ParserWarning,
  780. stacklevel=find_stack_level(),
  781. )
  782. @overload
  783. def _evaluate_usecols(
  784. self,
  785. usecols: set[int] | Callable[[Hashable], object],
  786. names: Sequence[Hashable],
  787. ) -> set[int]:
  788. ...
  789. @overload
  790. def _evaluate_usecols(
  791. self, usecols: set[str], names: Sequence[Hashable]
  792. ) -> set[str]:
  793. ...
  794. def _evaluate_usecols(
  795. self,
  796. usecols: Callable[[Hashable], object] | set[str] | set[int],
  797. names: Sequence[Hashable],
  798. ) -> set[str] | set[int]:
  799. """
  800. Check whether or not the 'usecols' parameter
  801. is a callable. If so, enumerates the 'names'
  802. parameter and returns a set of indices for
  803. each entry in 'names' that evaluates to True.
  804. If not a callable, returns 'usecols'.
  805. """
  806. if callable(usecols):
  807. return {i for i, name in enumerate(names) if usecols(name)}
  808. return usecols
  809. def _validate_usecols_names(self, usecols, names):
  810. """
  811. Validates that all usecols are present in a given
  812. list of names. If not, raise a ValueError that
  813. shows what usecols are missing.
  814. Parameters
  815. ----------
  816. usecols : iterable of usecols
  817. The columns to validate are present in names.
  818. names : iterable of names
  819. The column names to check against.
  820. Returns
  821. -------
  822. usecols : iterable of usecols
  823. The `usecols` parameter if the validation succeeds.
  824. Raises
  825. ------
  826. ValueError : Columns were missing. Error message will list them.
  827. """
  828. missing = [c for c in usecols if c not in names]
  829. if len(missing) > 0:
  830. raise ValueError(
  831. f"Usecols do not match columns, columns expected but not found: "
  832. f"{missing}"
  833. )
  834. return usecols
  835. def _validate_usecols_arg(self, usecols):
  836. """
  837. Validate the 'usecols' parameter.
  838. Checks whether or not the 'usecols' parameter contains all integers
  839. (column selection by index), strings (column by name) or is a callable.
  840. Raises a ValueError if that is not the case.
  841. Parameters
  842. ----------
  843. usecols : list-like, callable, or None
  844. List of columns to use when parsing or a callable that can be used
  845. to filter a list of table columns.
  846. Returns
  847. -------
  848. usecols_tuple : tuple
  849. A tuple of (verified_usecols, usecols_dtype).
  850. 'verified_usecols' is either a set if an array-like is passed in or
  851. 'usecols' if a callable or None is passed in.
  852. 'usecols_dtype` is the inferred dtype of 'usecols' if an array-like
  853. is passed in or None if a callable or None is passed in.
  854. """
  855. msg = (
  856. "'usecols' must either be list-like of all strings, all unicode, "
  857. "all integers or a callable."
  858. )
  859. if usecols is not None:
  860. if callable(usecols):
  861. return usecols, None
  862. if not is_list_like(usecols):
  863. # see gh-20529
  864. #
  865. # Ensure it is iterable container but not string.
  866. raise ValueError(msg)
  867. usecols_dtype = lib.infer_dtype(usecols, skipna=False)
  868. if usecols_dtype not in ("empty", "integer", "string"):
  869. raise ValueError(msg)
  870. usecols = set(usecols)
  871. return usecols, usecols_dtype
  872. return usecols, None
  873. def _clean_index_names(self, columns, index_col) -> tuple[list | None, list, list]:
  874. if not is_index_col(index_col):
  875. return None, columns, index_col
  876. columns = list(columns)
  877. # In case of no rows and multiindex columns we have to set index_names to
  878. # list of Nones GH#38292
  879. if not columns:
  880. return [None] * len(index_col), columns, index_col
  881. cp_cols = list(columns)
  882. index_names: list[str | int | None] = []
  883. # don't mutate
  884. index_col = list(index_col)
  885. for i, c in enumerate(index_col):
  886. if isinstance(c, str):
  887. index_names.append(c)
  888. for j, name in enumerate(cp_cols):
  889. if name == c:
  890. index_col[i] = j
  891. columns.remove(name)
  892. break
  893. else:
  894. name = cp_cols[c]
  895. columns.remove(name)
  896. index_names.append(name)
  897. # Only clean index names that were placeholders.
  898. for i, name in enumerate(index_names):
  899. if isinstance(name, str) and name in self.unnamed_cols:
  900. index_names[i] = None
  901. return index_names, columns, index_col
  902. def _get_empty_meta(
  903. self, columns, index_col, index_names, dtype: DtypeArg | None = None
  904. ):
  905. columns = list(columns)
  906. # Convert `dtype` to a defaultdict of some kind.
  907. # This will enable us to write `dtype[col_name]`
  908. # without worrying about KeyError issues later on.
  909. dtype_dict: defaultdict[Hashable, Any]
  910. if not is_dict_like(dtype):
  911. # if dtype == None, default will be object.
  912. default_dtype = dtype or object
  913. dtype_dict = defaultdict(lambda: default_dtype)
  914. else:
  915. dtype = cast(dict, dtype)
  916. dtype_dict = defaultdict(
  917. lambda: object,
  918. {columns[k] if is_integer(k) else k: v for k, v in dtype.items()},
  919. )
  920. # Even though we have no data, the "index" of the empty DataFrame
  921. # could for example still be an empty MultiIndex. Thus, we need to
  922. # check whether we have any index columns specified, via either:
  923. #
  924. # 1) index_col (column indices)
  925. # 2) index_names (column names)
  926. #
  927. # Both must be non-null to ensure a successful construction. Otherwise,
  928. # we have to create a generic empty Index.
  929. index: Index
  930. if (index_col is None or index_col is False) or index_names is None:
  931. index = default_index(0)
  932. else:
  933. data = [Series([], dtype=dtype_dict[name]) for name in index_names]
  934. index = ensure_index_from_sequences(data, names=index_names)
  935. index_col.sort()
  936. for i, n in enumerate(index_col):
  937. columns.pop(n - i)
  938. col_dict = {
  939. col_name: Series([], dtype=dtype_dict[col_name]) for col_name in columns
  940. }
  941. return index, columns, col_dict
  942. def _make_date_converter(
  943. date_parser=lib.no_default,
  944. dayfirst: bool = False,
  945. cache_dates: bool = True,
  946. date_format: dict[Hashable, str] | str | None = None,
  947. ):
  948. if date_parser is not lib.no_default:
  949. warnings.warn(
  950. "The argument 'date_parser' is deprecated and will "
  951. "be removed in a future version. "
  952. "Please use 'date_format' instead, or read your data in as 'object' dtype "
  953. "and then call 'to_datetime'.",
  954. FutureWarning,
  955. stacklevel=find_stack_level(),
  956. )
  957. if date_parser is not lib.no_default and date_format is not None:
  958. raise TypeError("Cannot use both 'date_parser' and 'date_format'")
  959. def unpack_if_single_element(arg):
  960. # NumPy 1.25 deprecation: https://github.com/numpy/numpy/pull/10615
  961. if isinstance(arg, np.ndarray) and arg.ndim == 1 and len(arg) == 1:
  962. return arg[0]
  963. return arg
  964. def converter(*date_cols, col: Hashable):
  965. if len(date_cols) == 1 and date_cols[0].dtype.kind in "Mm":
  966. return date_cols[0]
  967. if date_parser is lib.no_default:
  968. strs = parsing.concat_date_cols(date_cols)
  969. date_fmt = (
  970. date_format.get(col) if isinstance(date_format, dict) else date_format
  971. )
  972. result = tools.to_datetime(
  973. ensure_object(strs),
  974. format=date_fmt,
  975. utc=False,
  976. dayfirst=dayfirst,
  977. errors="ignore",
  978. cache=cache_dates,
  979. )
  980. if isinstance(result, DatetimeIndex):
  981. arr = result.to_numpy()
  982. arr.flags.writeable = True
  983. return arr
  984. return result._values
  985. else:
  986. try:
  987. result = tools.to_datetime(
  988. date_parser(*(unpack_if_single_element(arg) for arg in date_cols)),
  989. errors="ignore",
  990. cache=cache_dates,
  991. )
  992. if isinstance(result, datetime.datetime):
  993. raise Exception("scalar parser")
  994. return result
  995. except Exception:
  996. return tools.to_datetime(
  997. parsing.try_parse_dates(
  998. parsing.concat_date_cols(date_cols),
  999. parser=date_parser,
  1000. ),
  1001. errors="ignore",
  1002. )
  1003. return converter
  1004. parser_defaults = {
  1005. "delimiter": None,
  1006. "escapechar": None,
  1007. "quotechar": '"',
  1008. "quoting": csv.QUOTE_MINIMAL,
  1009. "doublequote": True,
  1010. "skipinitialspace": False,
  1011. "lineterminator": None,
  1012. "header": "infer",
  1013. "index_col": None,
  1014. "names": None,
  1015. "skiprows": None,
  1016. "skipfooter": 0,
  1017. "nrows": None,
  1018. "na_values": None,
  1019. "keep_default_na": True,
  1020. "true_values": None,
  1021. "false_values": None,
  1022. "converters": None,
  1023. "dtype": None,
  1024. "cache_dates": True,
  1025. "thousands": None,
  1026. "comment": None,
  1027. "decimal": ".",
  1028. # 'engine': 'c',
  1029. "parse_dates": False,
  1030. "keep_date_col": False,
  1031. "dayfirst": False,
  1032. "date_parser": lib.no_default,
  1033. "date_format": None,
  1034. "usecols": None,
  1035. # 'iterator': False,
  1036. "chunksize": None,
  1037. "verbose": False,
  1038. "encoding": None,
  1039. "compression": None,
  1040. "skip_blank_lines": True,
  1041. "encoding_errors": "strict",
  1042. "on_bad_lines": ParserBase.BadLineHandleMethod.ERROR,
  1043. "dtype_backend": lib.no_default,
  1044. }
  1045. def _process_date_conversion(
  1046. data_dict,
  1047. converter: Callable,
  1048. parse_spec,
  1049. index_col,
  1050. index_names,
  1051. columns,
  1052. keep_date_col: bool = False,
  1053. dtype_backend=lib.no_default,
  1054. ):
  1055. def _isindex(colspec):
  1056. return (isinstance(index_col, list) and colspec in index_col) or (
  1057. isinstance(index_names, list) and colspec in index_names
  1058. )
  1059. new_cols = []
  1060. new_data = {}
  1061. orig_names = columns
  1062. columns = list(columns)
  1063. date_cols = set()
  1064. if parse_spec is None or isinstance(parse_spec, bool):
  1065. return data_dict, columns
  1066. if isinstance(parse_spec, list):
  1067. # list of column lists
  1068. for colspec in parse_spec:
  1069. if is_scalar(colspec) or isinstance(colspec, tuple):
  1070. if isinstance(colspec, int) and colspec not in data_dict:
  1071. colspec = orig_names[colspec]
  1072. if _isindex(colspec):
  1073. continue
  1074. elif dtype_backend == "pyarrow":
  1075. import pyarrow as pa
  1076. dtype = data_dict[colspec].dtype
  1077. if isinstance(dtype, ArrowDtype) and (
  1078. pa.types.is_timestamp(dtype.pyarrow_dtype)
  1079. or pa.types.is_date(dtype.pyarrow_dtype)
  1080. ):
  1081. continue
  1082. # Pyarrow engine returns Series which we need to convert to
  1083. # numpy array before converter, its a no-op for other parsers
  1084. data_dict[colspec] = converter(
  1085. np.asarray(data_dict[colspec]), col=colspec
  1086. )
  1087. else:
  1088. new_name, col, old_names = _try_convert_dates(
  1089. converter, colspec, data_dict, orig_names
  1090. )
  1091. if new_name in data_dict:
  1092. raise ValueError(f"New date column already in dict {new_name}")
  1093. new_data[new_name] = col
  1094. new_cols.append(new_name)
  1095. date_cols.update(old_names)
  1096. elif isinstance(parse_spec, dict):
  1097. # dict of new name to column list
  1098. for new_name, colspec in parse_spec.items():
  1099. if new_name in data_dict:
  1100. raise ValueError(f"Date column {new_name} already in dict")
  1101. _, col, old_names = _try_convert_dates(
  1102. converter,
  1103. colspec,
  1104. data_dict,
  1105. orig_names,
  1106. target_name=new_name,
  1107. )
  1108. new_data[new_name] = col
  1109. # If original column can be converted to date we keep the converted values
  1110. # This can only happen if values are from single column
  1111. if len(colspec) == 1:
  1112. new_data[colspec[0]] = col
  1113. new_cols.append(new_name)
  1114. date_cols.update(old_names)
  1115. data_dict.update(new_data)
  1116. new_cols.extend(columns)
  1117. if not keep_date_col:
  1118. for c in list(date_cols):
  1119. data_dict.pop(c)
  1120. new_cols.remove(c)
  1121. return data_dict, new_cols
  1122. def _try_convert_dates(
  1123. parser: Callable, colspec, data_dict, columns, target_name: str | None = None
  1124. ):
  1125. colset = set(columns)
  1126. colnames = []
  1127. for c in colspec:
  1128. if c in colset:
  1129. colnames.append(c)
  1130. elif isinstance(c, int) and c not in columns:
  1131. colnames.append(columns[c])
  1132. else:
  1133. colnames.append(c)
  1134. new_name: tuple | str
  1135. if all(isinstance(x, tuple) for x in colnames):
  1136. new_name = tuple(map("_".join, zip(*colnames)))
  1137. else:
  1138. new_name = "_".join([str(x) for x in colnames])
  1139. to_parse = [np.asarray(data_dict[c]) for c in colnames if c in data_dict]
  1140. new_col = parser(*to_parse, col=new_name if target_name is None else target_name)
  1141. return new_name, new_col, colnames
  1142. def _get_na_values(col, na_values, na_fvalues, keep_default_na):
  1143. """
  1144. Get the NaN values for a given column.
  1145. Parameters
  1146. ----------
  1147. col : str
  1148. The name of the column.
  1149. na_values : array-like, dict
  1150. The object listing the NaN values as strings.
  1151. na_fvalues : array-like, dict
  1152. The object listing the NaN values as floats.
  1153. keep_default_na : bool
  1154. If `na_values` is a dict, and the column is not mapped in the
  1155. dictionary, whether to return the default NaN values or the empty set.
  1156. Returns
  1157. -------
  1158. nan_tuple : A length-two tuple composed of
  1159. 1) na_values : the string NaN values for that column.
  1160. 2) na_fvalues : the float NaN values for that column.
  1161. """
  1162. if isinstance(na_values, dict):
  1163. if col in na_values:
  1164. return na_values[col], na_fvalues[col]
  1165. else:
  1166. if keep_default_na:
  1167. return STR_NA_VALUES, set()
  1168. return set(), set()
  1169. else:
  1170. return na_values, na_fvalues
  1171. def _validate_parse_dates_arg(parse_dates):
  1172. """
  1173. Check whether or not the 'parse_dates' parameter
  1174. is a non-boolean scalar. Raises a ValueError if
  1175. that is the case.
  1176. """
  1177. msg = (
  1178. "Only booleans, lists, and dictionaries are accepted "
  1179. "for the 'parse_dates' parameter"
  1180. )
  1181. if parse_dates is not None:
  1182. if is_scalar(parse_dates):
  1183. if not lib.is_bool(parse_dates):
  1184. raise TypeError(msg)
  1185. elif not isinstance(parse_dates, (list, dict)):
  1186. raise TypeError(msg)
  1187. return parse_dates
  1188. def is_index_col(col) -> bool:
  1189. return col is not None and col is not False