csvs.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. """
  2. Module for formatting output data into CSV files.
  3. """
  4. from __future__ import annotations
  5. import csv as csvlib
  6. import os
  7. from typing import (
  8. TYPE_CHECKING,
  9. Any,
  10. Hashable,
  11. Iterator,
  12. Sequence,
  13. cast,
  14. )
  15. import numpy as np
  16. from pandas._libs import writers as libwriters
  17. from pandas._typing import (
  18. CompressionOptions,
  19. FilePath,
  20. FloatFormatType,
  21. IndexLabel,
  22. StorageOptions,
  23. WriteBuffer,
  24. )
  25. from pandas.util._decorators import cache_readonly
  26. from pandas.core.dtypes.generic import (
  27. ABCDatetimeIndex,
  28. ABCIndex,
  29. ABCMultiIndex,
  30. ABCPeriodIndex,
  31. )
  32. from pandas.core.dtypes.missing import notna
  33. from pandas.core.indexes.api import Index
  34. from pandas.io.common import get_handle
  35. if TYPE_CHECKING:
  36. from pandas.io.formats.format import DataFrameFormatter
  37. class CSVFormatter:
  38. cols: np.ndarray
  39. def __init__(
  40. self,
  41. formatter: DataFrameFormatter,
  42. path_or_buf: FilePath | WriteBuffer[str] | WriteBuffer[bytes] = "",
  43. sep: str = ",",
  44. cols: Sequence[Hashable] | None = None,
  45. index_label: IndexLabel | None = None,
  46. mode: str = "w",
  47. encoding: str | None = None,
  48. errors: str = "strict",
  49. compression: CompressionOptions = "infer",
  50. quoting: int | None = None,
  51. lineterminator: str | None = "\n",
  52. chunksize: int | None = None,
  53. quotechar: str | None = '"',
  54. date_format: str | None = None,
  55. doublequote: bool = True,
  56. escapechar: str | None = None,
  57. storage_options: StorageOptions = None,
  58. ) -> None:
  59. self.fmt = formatter
  60. self.obj = self.fmt.frame
  61. self.filepath_or_buffer = path_or_buf
  62. self.encoding = encoding
  63. self.compression: CompressionOptions = compression
  64. self.mode = mode
  65. self.storage_options = storage_options
  66. self.sep = sep
  67. self.index_label = self._initialize_index_label(index_label)
  68. self.errors = errors
  69. self.quoting = quoting or csvlib.QUOTE_MINIMAL
  70. self.quotechar = self._initialize_quotechar(quotechar)
  71. self.doublequote = doublequote
  72. self.escapechar = escapechar
  73. self.lineterminator = lineterminator or os.linesep
  74. self.date_format = date_format
  75. self.cols = self._initialize_columns(cols)
  76. self.chunksize = self._initialize_chunksize(chunksize)
  77. @property
  78. def na_rep(self) -> str:
  79. return self.fmt.na_rep
  80. @property
  81. def float_format(self) -> FloatFormatType | None:
  82. return self.fmt.float_format
  83. @property
  84. def decimal(self) -> str:
  85. return self.fmt.decimal
  86. @property
  87. def header(self) -> bool | Sequence[str]:
  88. return self.fmt.header
  89. @property
  90. def index(self) -> bool:
  91. return self.fmt.index
  92. def _initialize_index_label(self, index_label: IndexLabel | None) -> IndexLabel:
  93. if index_label is not False:
  94. if index_label is None:
  95. return self._get_index_label_from_obj()
  96. elif not isinstance(index_label, (list, tuple, np.ndarray, ABCIndex)):
  97. # given a string for a DF with Index
  98. return [index_label]
  99. return index_label
  100. def _get_index_label_from_obj(self) -> Sequence[Hashable]:
  101. if isinstance(self.obj.index, ABCMultiIndex):
  102. return self._get_index_label_multiindex()
  103. else:
  104. return self._get_index_label_flat()
  105. def _get_index_label_multiindex(self) -> Sequence[Hashable]:
  106. return [name or "" for name in self.obj.index.names]
  107. def _get_index_label_flat(self) -> Sequence[Hashable]:
  108. index_label = self.obj.index.name
  109. return [""] if index_label is None else [index_label]
  110. def _initialize_quotechar(self, quotechar: str | None) -> str | None:
  111. if self.quoting != csvlib.QUOTE_NONE:
  112. # prevents crash in _csv
  113. return quotechar
  114. return None
  115. @property
  116. def has_mi_columns(self) -> bool:
  117. return bool(isinstance(self.obj.columns, ABCMultiIndex))
  118. def _initialize_columns(self, cols: Sequence[Hashable] | None) -> np.ndarray:
  119. # validate mi options
  120. if self.has_mi_columns:
  121. if cols is not None:
  122. msg = "cannot specify cols with a MultiIndex on the columns"
  123. raise TypeError(msg)
  124. if cols is not None:
  125. if isinstance(cols, ABCIndex):
  126. cols = cols._format_native_types(**self._number_format)
  127. else:
  128. cols = list(cols)
  129. self.obj = self.obj.loc[:, cols]
  130. # update columns to include possible multiplicity of dupes
  131. # and make sure cols is just a list of labels
  132. new_cols = self.obj.columns
  133. return new_cols._format_native_types(**self._number_format)
  134. def _initialize_chunksize(self, chunksize: int | None) -> int:
  135. if chunksize is None:
  136. return (100000 // (len(self.cols) or 1)) or 1
  137. return int(chunksize)
  138. @property
  139. def _number_format(self) -> dict[str, Any]:
  140. """Dictionary used for storing number formatting settings."""
  141. return {
  142. "na_rep": self.na_rep,
  143. "float_format": self.float_format,
  144. "date_format": self.date_format,
  145. "quoting": self.quoting,
  146. "decimal": self.decimal,
  147. }
  148. @cache_readonly
  149. def data_index(self) -> Index:
  150. data_index = self.obj.index
  151. if (
  152. isinstance(data_index, (ABCDatetimeIndex, ABCPeriodIndex))
  153. and self.date_format is not None
  154. ):
  155. data_index = Index(
  156. [x.strftime(self.date_format) if notna(x) else "" for x in data_index]
  157. )
  158. elif isinstance(data_index, ABCMultiIndex):
  159. data_index = data_index.remove_unused_levels()
  160. return data_index
  161. @property
  162. def nlevels(self) -> int:
  163. if self.index:
  164. return getattr(self.data_index, "nlevels", 1)
  165. else:
  166. return 0
  167. @property
  168. def _has_aliases(self) -> bool:
  169. return isinstance(self.header, (tuple, list, np.ndarray, ABCIndex))
  170. @property
  171. def _need_to_save_header(self) -> bool:
  172. return bool(self._has_aliases or self.header)
  173. @property
  174. def write_cols(self) -> Sequence[Hashable]:
  175. if self._has_aliases:
  176. assert not isinstance(self.header, bool)
  177. if len(self.header) != len(self.cols):
  178. raise ValueError(
  179. f"Writing {len(self.cols)} cols but got {len(self.header)} aliases"
  180. )
  181. return self.header
  182. else:
  183. # self.cols is an ndarray derived from Index._format_native_types,
  184. # so its entries are strings, i.e. hashable
  185. return cast(Sequence[Hashable], self.cols)
  186. @property
  187. def encoded_labels(self) -> list[Hashable]:
  188. encoded_labels: list[Hashable] = []
  189. if self.index and self.index_label:
  190. assert isinstance(self.index_label, Sequence)
  191. encoded_labels = list(self.index_label)
  192. if not self.has_mi_columns or self._has_aliases:
  193. encoded_labels += list(self.write_cols)
  194. return encoded_labels
  195. def save(self) -> None:
  196. """
  197. Create the writer & save.
  198. """
  199. # apply compression and byte/text conversion
  200. with get_handle(
  201. self.filepath_or_buffer,
  202. self.mode,
  203. encoding=self.encoding,
  204. errors=self.errors,
  205. compression=self.compression,
  206. storage_options=self.storage_options,
  207. ) as handles:
  208. # Note: self.encoding is irrelevant here
  209. self.writer = csvlib.writer(
  210. handles.handle,
  211. lineterminator=self.lineterminator,
  212. delimiter=self.sep,
  213. quoting=self.quoting,
  214. doublequote=self.doublequote,
  215. escapechar=self.escapechar,
  216. quotechar=self.quotechar,
  217. )
  218. self._save()
  219. def _save(self) -> None:
  220. if self._need_to_save_header:
  221. self._save_header()
  222. self._save_body()
  223. def _save_header(self) -> None:
  224. if not self.has_mi_columns or self._has_aliases:
  225. self.writer.writerow(self.encoded_labels)
  226. else:
  227. for row in self._generate_multiindex_header_rows():
  228. self.writer.writerow(row)
  229. def _generate_multiindex_header_rows(self) -> Iterator[list[Hashable]]:
  230. columns = self.obj.columns
  231. for i in range(columns.nlevels):
  232. # we need at least 1 index column to write our col names
  233. col_line = []
  234. if self.index:
  235. # name is the first column
  236. col_line.append(columns.names[i])
  237. if isinstance(self.index_label, list) and len(self.index_label) > 1:
  238. col_line.extend([""] * (len(self.index_label) - 1))
  239. col_line.extend(columns._get_level_values(i))
  240. yield col_line
  241. # Write out the index line if it's not empty.
  242. # Otherwise, we will print out an extraneous
  243. # blank line between the mi and the data rows.
  244. if self.encoded_labels and set(self.encoded_labels) != {""}:
  245. yield self.encoded_labels + [""] * len(columns)
  246. def _save_body(self) -> None:
  247. nrows = len(self.data_index)
  248. chunks = (nrows // self.chunksize) + 1
  249. for i in range(chunks):
  250. start_i = i * self.chunksize
  251. end_i = min(start_i + self.chunksize, nrows)
  252. if start_i >= end_i:
  253. break
  254. self._save_chunk(start_i, end_i)
  255. def _save_chunk(self, start_i: int, end_i: int) -> None:
  256. # create the data for a chunk
  257. slicer = slice(start_i, end_i)
  258. df = self.obj.iloc[slicer]
  259. res = df._mgr.to_native_types(**self._number_format)
  260. data = [res.iget_values(i) for i in range(len(res.items))]
  261. ix = self.data_index[slicer]._format_native_types(**self._number_format)
  262. libwriters.write_csv_rows(
  263. data,
  264. ix,
  265. self.nlevels,
  266. self.cols,
  267. self.writer,
  268. )