Python pandas: pandas.DataFrame.to_ The brief introduction, concrete case and usage method of CSV function

A Virgo procedural ape 2020-11-13 05:49:00
python pandas pandas.dataframe.to_ pandas dataframe


Python And Pandas:pandas.DataFrame.to_csv Function introduction 、 Specific cases 、 Detailed introduction of usage

 

 

 

 

Catalog

pandas.DataFrame.to_csv Function introduction

pandas.to_csv() Specific cases of functions


 

 

 

pandas.DataFrame.to_csv Function introduction

DataFrame.to_csv(path_or_buf=Nonesep=','na_rep=''float_format=Nonecolumns=Noneheader=Trueindex=Trueindex_label=Nonemode='w'encoding=Nonecompression='infer'quoting=Nonequotechar='"'line_terminator=Nonechunksize=Nonedate_format=Nonedoublequote=Trueescapechar=Nonedecimal='.'errors='strict')

def to_csv Found at: 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_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.

Write objects to comma separated values (csv) file .

    Parameters
    ----------
    path_or_buf : str 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.
    .. versionchanged:: 0.24.0
    Was previously named "path" for Series.
    
    sep : str, default ','. String of length 1. Field delimiter for the output file.
    na_rep : str, default ''. Missing data representation.
    float_format : str, default None. Format string for floating point numbers.
    columns : sequence, optional. Columns to write.
    header : bool 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.
    .. versionchanged:: 0.24.0
    Previously defaulted to False for Series.
    
    index : bool, default True. Write row names (index).
    index_label : str 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.
    mode : str.Python write mode, default 'w'.
    encoding : str, optional.A string representing the encoding to use in the output file, defaults to 'utf-8'.
    compression : str 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 one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above, other entries passed as additional compression options.

   .. versionchanged:: 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'.
    .. versionchanged:: 1.1.0
    Passing compression options as keys in dict is  supported for compression modes 'gzip' and 'bz2'  as well as 'zip'.

Parameters
----------
path_or_buf :  str or file handle, The default is no . File path or object , If not provided , The result will be returned as a string . If a file object is passed , It should be opened ' newline= " ', Disable universal line feed .
. .versionchanged: 0.24.0
It was previously named “path” series .

sep : str, The default is ','. The length is 1 String . Field separator for output file .
na_rep :  str, The default value is ". Missing data means .
float_format :  str, There is no default . Floating point format string .
columns :   Sequence , Optional . Column writing .
header :  bool or str list , The default is True. Write column names . If given a list of strings , It is assumed to be an alias for the column name .
. .versionchanged: 0.24.0
Previously, the default for series was False.

index :  bool, The default is True. Write the line name ( Indexes ).
iindex_label :  str Or sequence , or False, The default is no . if necessary , Column labels for indexed columns . If not given , also ' header ' and ' index ' It's true , Then use the index name . If the object uses multiple indexes , You should give a sequence . If False, Don't print the index name field . Use index_label=False stay R It's easier to import .
mode : str.Python Writing mode , The default is “w”.
encoding : str, Optional . A string representing the encoding to be used in the output file , The default is “utf-8”.
compression : str or dict, The default is 'infer'. If str, Represents the compression mode . If it is dict, value at 'method' It's compression mode . Compression mode can be any of the following
possible values:   {'infer', 'gzip', 'bz2', 'zip', 'xz', None}.. If the compression mode is 'infer', and ' path_or_buf ' It's similar to the path , Then check the compression mode from the following extension :'. '. gz', '.bz2', '.zip' or '.xz'. .( Otherwise, it doesn't compress ). If dict given and mode yes {'zip'、'gzip'、'bz2'} Or inferred as one of the above options , Other items are passed as additional compression options .

. .versionchanged: 1.0.0
If the compression mode is “zip”, You can use the key “ Method ” As a compression mode , Other entries as additional compression options .
. .versionchanged: 1.1.0
Compression mode “gzip” and “bz2” as well as “zip” Support compression options as keys in dict In the transfer .

   quoting : optional 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.
    quotechar : str, default '\"'. String of length 1. Character used to quote fields.
    line_terminator : str, 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, '\r\n' for Windows, i.e.).
    .. versionchanged:: 0.24.0
    chunksize : int or None. Rows to write at a time.
    date_format : str, default None.Format string for datetime objects.
    doublequote : bool, default True. Control quoting of `quotechar` inside a field.
    escapechar : str, default None. String of length 1. Character used to escape `sep` and  `quotechar` when appropriate.
    decimal : str, default '.'. Character recognized as decimal separator. E.g. use ',' for European data.
    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

quoting :  csv Optional constants in the module . The default is csv.QUOTE_MINIMAL. If you set up a ' float_format ', that float Will be converted to a string , To convert to csv.QUOTE_NONNUMERIC They will be treated as non numerical .
quoting : str, The default is '\"'. The length is 1 String . The character used to refer to the field .
line_terminator : str, Optional . The newline character or character sequence to be used in the output file . The default operating system .linesep ', It depends on the operating system that calls the method ( for example ,linux yes '\n', Windows yes '\r\n').
. .versionchanged: 0.24.0
chunksize : int or None. The lines to be written each time .
date_format :  str, The default is no . Format string of date time object .
doublequote :bool, The default is True. Control field reference “quotechar”.
escapechar : str, The default is no . The length is 1 String . At the right time , Characters are used to escape ' sep ' and ' quotechar '.
decimal :  str, The default is '.'. A character recognized as a decimal separator . for example , Use “,” For European data .
errors :  str, The default is “strict”. Specifies how encoding and decoding errors are handled . see :func: ' open ' To get a complete list of options .
. .versionadded: 1.1.0
    Returns
    -------
    None or str.  If path_or_buf is None, returns the resulting csv format as a string. Otherwise returns None.
    
    See Also
    --------
    read_csv : Load a CSV file into a DataFrame.
    to_excel : Write DataFrame to an Excel file.
return
-------
If path_or_buf by None, Returns the result csv The format is string . Otherwise return to None.

See also
 --------
read_csv: take CSV File loaded into a DataFrame in .
to_excel: take DataFrame write in Excel file .

    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)  # 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() Specific cases of functions

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) 

 

 

 

 

 

版权声明
本文为[A Virgo procedural ape]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database