Python之Pandas:pandas.DataFrame.to_csv函数的简介、具体案例、使用方法详细攻略
pandas.DataFrame.to_csv函数的简介
DataFrame.to_csv(path_or_buf=None, sep=',', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, quotechar='\"', line_terminator=None, chunksize=None, date_format=None, doublequote=True, escapechar=None, decimal='.', errors='strict')
def to_csv pandas.core.generic def to_csv( self, path_or_buf:Optional[FilePathOrBuffer]=None, sep:str=\ na_rep:str=\"\ float_format:Optional[str]=None, columns:Optional[Sequence[Label]]=None, header:Union[bool_tList[str]]=True, index:bool_t=True, index_label:Optional[Union[bool_将对象写入逗号分隔值(csv)文件。 Found at: tstrSequence[Label]]] =None, mode:str=\"w\ encoding:Optional[str]=None, compression:Optional[Union[strMapping[strstr]]]=\"infer\ quoting:Optional[int]=None, quotechar:str='\"', line_terminator:Optional[str]=None, chunksize:Optional[int]=None, date_format:Optional[str]=None, doublequote:bool_t=True, escapechar:Optional[str]=None, decimal:Optional[str]=\".\ errors:str=\"strict\")-> Optional[str]: r\"\"\" Write object to a comma-separated values (csv) file. .. versionchanged:: 0.24.0 The order of arguments for Series was changed. Parameters 参数 ---------- ---------- path_or_buf : str or file handle, path_or_buf : str或file default None. File path or object, if handle,默认无。文件路径或对None is provided the result is 象,如果没有提供,结果将作为returned as a string. If a file 字符串返回。如果一个文件对象object is passed it should be opened 被传递,它应该被打开' with `newline=''`, disabling universal newline= \" ',禁用通用换行。 newlines. . .versionchanged: 0.24.0 .. versionchanged:: 0.24.0 之前被命名为“path”系列。 Was previously named \"path\" for Series. sep : str,默认为','。长度为1的字符串。输出文件的字段分隔 sep : str, default ','. String of 符。 length 1. Field delimiter for the na_rep : str,默认值\"。缺失output file. 的数据表示。 na_rep : str, default ''. Missing float_format : str,默认没data representation. 有。浮点数的格式字符串。 float_format : str, default None. Format string for floating point columns : 序列,可选。列写。 numbers. columns : sequence, optional. header : bool或str列表,默认为True。写出列名。如果给Columns to write. 定了字符串列表,则假定它是列 header : bool or list of str, 名的别名。 default True.Write out the column names. If a list of strings is given it . .versionchanged: 0.24.0 is assumed to be aliases for the column 以前对于级数默认为False。 names. .. versionchanged:: 0.24.0 Previously defaulted to False for index : bool,默认为True。写行名称(索引)。 Series. index : bool, default True. Write • cats_df_temp.to_csv(cats_csv_file,index=None) #输出不加默认的索row names (index). 引列 index_label : str or sequence, or iindex_label : str或序列,False, default None. Column label for 或False,默认无。如果需要,用index column(s) if desired. If None is 于索引列的列标签。如果没有给given, and `header` and `index` are 出,并且' header '和' index 'True, then the index names are 为真,则使用索引名。如果对象used. A sequence should be given if 使用多索引,则应该给出一个序the object uses MultiIndex. If False 列。如果为False,不要打印索引do not print fields for index names. 名称的字段。使用Use index_label=False for easier index_label=False在R中更容易importing in R. 导入。 mode : str.Python write mode, mode : str.Python编写模式,default 'w'. 默认为“w”。 encoding : str, optional.A string encoding : str,可选。表示要representing the encoding to use in the 在输出文件中使用的编码的字符output file, defaults to 'utf-8'. 串,默认为“utf-8”。 compression : str or dict, compression : str或dict,默default 'infer'. If str, represents 认为'infer'。如果为str,表示compression mode. If dict, value at 压缩模式。如果是dict, value 'method' is the compression mode. at 'method'是压缩模式。压缩模Compression mode may be any of the 式可以是下列任何一种 following possible values: {'infer', possible values: {'infer', 'gzip', 'bz2', 'zip', 'xz', 'gzip', 'bz2', 'zip', 'xz', None}. If None}.。如果压缩模式是compression mode is 'infer' and 'infer',而' path_or_buf '是类`path_or_buf` is path-like, then 似路径的,那么从以下扩展中检detect compression mode from the 测压缩模式:'。 '. gz', '.bz2', following extensions: '. gz', '.bz2', '.zip' or '.xz'. 。(否则不压'.zip' or '.xz'. (otherwise no 缩)。如果dict given和mode是compression). If dict given and mode {'zip'、'gzip'、'bz2'}或推断is one of {'zip', 'gzip', 'bz2'}, or 为上述选项之一,则其他项作为inferred as one of the above, other 附加压缩选项传递。 entries passed as additional . .versionchanged: 1.0.0 compression options. 如果压缩模式是“zip”,则可以使用关键的“方法”作为压缩模 May now be a dict with key 式,其他条目作为附加的压缩选'method' as compression mode and other 项。 entries as additional compression .. versionchanged:: 1.0.0 options if compression mode is 'zip'. . .versionchanged: 1.1.0 .. versionchanged:: 1.1.0 压缩模式“gzip”和“bz2”以及“zip”支持将压缩选项作为键在 Passing compression options as dict中传递。 keys in dict is supported for compression modes 'gzip' and 'bz2' as well as 'zip'. quoting : optional constant from quoting : csv模块中的可选量。默认为csv module. Defaults to 常csv.QUOTE_MINIMAL. If you have set csv.QUOTE_MINIMAL。如果你设置a `float_format` then floats are 了一个' float_format ',那么converted to strings and thus csv. float就会被转换为字符串,从而QUOTE_NONNUMERIC will treat them as 转换为csv。QUOTE_NONNUMERIC将把它们视为非数值。 non-numeric. quoting : str,默认为'\\\"'。长 quotechar : str, default '\\\"'. 度为1的字符串。用于引用字段的String of length 1. Character used to 字符。 line_terminator : str,可选。quote fields. 输出文件中要使用的换行字符或 line_terminator : str, optional. 字符序列。默认的操作系统。The newline character or character linesep ',它取决于调用该方法sequence to use in the output file. 的操作系统(例如,linux是Defaults to `os.linesep`, which depends '\\n', Windows是'\\r\\n')。 on the OS in which this method is called . .versionchanged: 0.24.0 ('\\n' for linux, '\\r\\n' for Windows, chunksize : int或None。每次要写入的行。 i.e.). date_format : str,默认无。日期时间对象的格式字符 .. versionchanged:: 0.24.0 串。 chunksize : int or None. Rows to doublequote :bool,默认为write at a time. True。控制字段内引用“quotechar”。 date_format : str, default escapechar : str,默认无。长None.Format string for datetime 度为1的字符串。在适当的时候,objects. 字符用于转义' sep '和' quotechar '。 doublequote : bool, default True. decimal : str,默认为'.'。Control quoting of `quotechar` inside 可识别为十进制分隔符的字符。a field. 例如,使用“,”表示欧洲数据。 escapechar : str, default None. errors : str,默认为String of length 1. Character used to “strict”。指定如何处理编码escape `sep` and `quotechar` when 和解码错误。查看:func: ' open '的错误参数以获得选项的完整列表。 decimal : str, default '.'. . .versionadded: 1.1.0 Character recognized as decimal separator. E.g. use ',' for European data. appropriate. errors : str, default 'strict'.Specifies how encoding and decoding errors are to be handled. See the errors argument for :func:`open` for a full list of options. .. versionadded:: 1.1.0 Returns 返回 ------- ------- None or str. If path_or_buf is 如果path_or_buf为None,则返None, returns the resulting csv format 回结果csv格式为字符串。否则返as a string. Otherwise returns None. 回None。 See Also 另请参阅 -------- -------- read_csv : Load a CSV file into read_csv:将CSV文件加载到一个a DataFrame. DataFrame中。 to_excel : Write DataFrame to an to_excel:将DataFrame写入Excel file. Excel文件。 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 >>> index=False, df.to_csv('out.zip', ... compression=compression_opts) # doctest: +SKIP \"\"\" df = self if isinstance(self, ABCDataFrame) else self.to_frame() from pandas.io.formats.csvs import CSVFormatter formatter = CSVFormatter( df, path_or_buf, line_terminator=line_terminator, sep=sep, encoding=encoding, errors=errors, compression=compression, quoting=quoting, na_rep=na_rep, float_format=float_format, cols=columns, header=header, index=index, index_label=index_label, mode=mode, chunksize=chunksize, quotechar=quotechar, date_format=date_format, doublequote=doublequote, escapechar=escapechar, decimal=decimal) formatter.save() if path_or_buf is None: return formatter.path_or_buf.getvalue() return None # ---------------------------------------------------------------------- # Lookup Caching pandas.to_csv()函数的具体案例
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'
compression_opts = dict(method='zip', archive_name='out.csv') df.to_csv('out.zip', index=False, compression=compression_opts)
因篇幅问题不能全部显示,请点此查看更多更全内容