pandas.DataFrame.to_csv¶
-
DataFrame.
to_csv
(self, path_or_buf: Union[str, pathlib.Path, IO[~AnyStr], NoneType] = None, sep: str = ',', na_rep: str = '', float_format: Union[str, NoneType] = None, columns: Union[Sequence[Union[Hashable, NoneType]], NoneType] = None, header: Union[bool, List[str]] = True, index: bool = True, index_label: Union[bool, str, Sequence[Union[Hashable, NoneType]], NoneType] = None, mode: str = 'w', encoding: Union[str, NoneType] = None, compression: Union[str, Mapping[str, str], NoneType] = 'infer', quoting: Union[int, NoneType] = None, quotechar: str = '"', line_terminator: Union[str, NoneType] = None, chunksize: Union[int, NoneType] = None, date_format: Union[str, NoneType] = None, doublequote: bool = True, escapechar: Union[str, NoneType] = None, decimal: Union[str, NoneType] = '.') → Union[str, NoneType][source]¶ Write object to a comma-separated values (csv) file.
Changed in version 0.24.0: The order of arguments for Series was changed.
- Parameters
- path_or_bufstr or file handle, default None
File path or object, if None is provided the result is returned as a string. If a file object is passed it should be opened with newline=’’, disabling universal newlines.
Changed in version 0.24.0: Was previously named “path” for Series.
- sepstr, default ‘,’
String of length 1. Field delimiter for the output file.
- na_repstr, default ‘’
Missing data representation.
- float_formatstr, default None
Format string for floating point numbers.
- columnssequence, optional
Columns to write.
- headerbool or list of str, default True
Write out the column names. If a list of strings is given it is assumed to be aliases for the column names.
Changed in version 0.24.0: Previously defaulted to False for Series.
- indexbool, default True
Write row names (index).
- index_labelstr or sequence, or False, default None
Column label for index column(s) if desired. If None is given, and header and index are True, then the index names are used. A sequence should be given if the object uses MultiIndex. If False do not print fields for index names. Use index_label=False for easier importing in R.
- modestr
Python write mode, default ‘w’.
- encodingstr, optional
A string representing the encoding to use in the output file, defaults to ‘utf-8’.
- compressionstr or dict, default ‘infer’
If str, represents compression mode. If dict, value at ‘method’ is the compression mode. Compression mode may be any of the following possible values: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}. If compression mode is ‘infer’ and path_or_buf is path-like, then detect compression mode from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’ or ‘.xz’. (otherwise no compression). If dict given and mode is ‘zip’ or inferred as ‘zip’, other entries passed as additional compression options.
Changed in version 1.0.0: May now be a dict with key ‘method’ as compression mode and other entries as additional compression options if compression mode is ‘zip’.
- quotingoptional constant from csv module
Defaults to csv.QUOTE_MINIMAL. If you have set a float_format then floats are converted to strings and thus csv.QUOTE_NONNUMERIC will treat them as non-numeric.
- quotecharstr, default ‘”’
String of length 1. Character used to quote fields.
- line_terminatorstr, optional
The newline character or character sequence to use in the output file. Defaults to os.linesep, which depends on the OS in which this method is called (‘n’ for linux, ‘rn’ for Windows, i.e.).
Changed in version 0.24.0.
- chunksizeint or None
Rows to write at a time.
- date_formatstr, default None
Format string for datetime objects.
- doublequotebool, default True
Control quoting of quotechar inside a field.
- escapecharstr, default None
String of length 1. Character used to escape sep and quotechar when appropriate.
- decimalstr, default ‘.’
Character recognized as decimal separator. E.g. use ‘,’ for European data.
- Returns
- None or str
If path_or_buf is None, returns the resulting csv format as a string. Otherwise returns None.
Examples
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'], ... 'mask': ['red', 'purple'], ... 'weapon': ['sai', 'bo staff']}) >>> df.to_csv(index=False) 'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
# create ‘out.zip’ containing ‘out.csv’ >>> compression_opts = dict(method=’zip’, … archive_name=’out.csv’) # doctest: +SKIP
>>> df.to_csv('out.zip', index=False, ... compression=compression_opts)