日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python之Pandas:pandas.DataFrame.to_csv函数的简介、具体案例、使用方法详细攻略

發布時間:2025/3/21 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python之Pandas:pandas.DataFrame.to_csv函数的简介、具体案例、使用方法详细攻略 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python之Pandas:pandas.DataFrame.to_csv函數的簡介、具體案例、使用方法詳細攻略

?

?

?

?

目錄

pandas.DataFrame.to_csv函數的簡介

pandas.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 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.

將對象寫入逗號分隔值(csv)文件

? ? 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'.

參數
----------
path_or_buf :??str或file handle,默認無。文件路徑或對象,如果沒有提供,結果將作為字符串返回。如果一個文件對象被傳遞,它應該被打開' newline= " ',禁用通用換行。
. .versionchanged: 0.24.0
之前被命名為“path”系列。

sep : str,默認為','。長度為1的字符串。輸出文件的字段分隔符
na_rep :? str,默認值"。缺失的數據表示
float_format :??str,默認沒有。浮點數的格式字符串
columns :??序列,可選。列寫。
header :??bool或str列表,默認為True。寫出列名。如果給定了字符串列表,則假定它是列名的別名
. .versionchanged: 0.24.0
以前對于級數默認為False。

index :??bool,默認為True。寫行名稱(索引)

  • cats_df_temp.to_csv(cats_csv_file,index=None)?? #輸出不加默認的索引列

iindex_label :? str或序列,或False,默認無。如果需要,用于索引列的列標簽。如果沒有給出,并且' header '和' index '為真,則使用索引名。如果對象使用多索引,則應該給出一個序列。如果為False,不要打印索引名稱的字段。使用index_label=False在R中更容易導入。
mode :?str.Python編寫模式,默認為“w”。
encoding :?str,可選。表示要在輸出文件中使用的編碼的字符串,默認為“utf-8”。
compression :?str或dict,默認為'infer'。如果為str,表示壓縮模式。如果是dict, value at 'method'是壓縮模式。壓縮模式可以是下列任何一種
possible values:? ?{'infer', 'gzip', 'bz2', 'zip', 'xz', None}.。如果壓縮模式是'infer',而' path_or_buf '是類似路徑的,那么從以下擴展中檢測壓縮模式:'。 '. gz', '.bz2', '.zip' or '.xz'. 。(否則不壓縮)。如果dict given和mode是{'zip'、'gzip'、'bz2'}或推斷為上述選項之一,則其他項作為附加壓縮選項傳遞。

. .versionchanged: 1.0.0
如果壓縮模式是“zip”,則可以使用關鍵的“方法”作為壓縮模式,其他條目作為附加的壓縮選項。
. .versionchanged: 1.1.0
壓縮模式“gzip”和“bz2”以及“zip”支持將壓縮選項作為鍵在dict中傳遞。

? ?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模塊中的可選常量。默認為csv.QUOTE_MINIMAL。如果你設置了一個' float_format ',那么float就會被轉換為字符串,從而轉換為csv。QUOTE_NONNUMERIC將把它們視為非數值。
quoting : str,默認為'\"'。長度為1的字符串。用于引用字段的字符
line_terminator : str,可選。輸出文件中要使用的換行字符或字符序列。默認的操作系統。linesep ',它取決于調用該方法的操作系統(例如,linux是'\n', Windows是'\r\n')。
. .versionchanged: 0.24.0
chunksize :?int或None。每次要寫入的行
date_format :??str,默認無。日期時間對象的格式字符串。
doublequote :bool,默認為True。控制字段內引用“quotechar”。
escapechar :?str,默認無。長度為1的字符串。在適當的時候,字符用于轉義' sep '和' quotechar '
decimal :??str,默認為'.'。可識別為十進制分隔符的字符。例如,使用“,”表示歐洲數據。
errors :??str,默認為“strict”。指定如何處理編碼和解碼錯誤。查看:func: ' open '的錯誤參數以獲得選項的完整列表。
. .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.
返回
-------
如果path_or_buf為None,則返回結果csv格式為字符串。否則返回None。

另請參閱
?--------
read_csv:將CSV文件加載到一個DataFrame中。
to_excel:將DataFrame寫入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
? ? >>> 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()函數的具體案例

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)

?

?

?

?

?

總結

以上是生活随笔為你收集整理的Python之Pandas:pandas.DataFrame.to_csv函数的简介、具体案例、使用方法详细攻略的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。