如何将 Pandas DataFrame 导出到 CSV 文件?
让我们看看如何将 Pandas DataFrame 导出为 CSV 文件。我们将使用to_csv()
函数将 DataFrame 保存为 CSV 文件。
DataFrame.to_csv()
Syntax : to_csv(parameters)
Parameters :
- path_or_buf : File path or object, if None is provided the result is returned as a string.
- sep : String of length 1. Field delimiter for the output file.
- na_rep : Missing data representation.
- float_format : Format string for floating point numbers.
- columns : Columns to write.
- header : If a list of strings is given it is assumed to be aliases for the column names.
- index : Write row names (index).
- index_label : Column label for index column(s) if desired. If None is given, and header and index are True, then the index names are used.
- mode : Python write mode, default ‘w’.
- encoding : A string representing the encoding to use in the output file.
- compression : Compression mode among the following possible values: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}.
- quoting : Defaults to csv.QUOTE_MINIMAL.
- quotechar : String of length 1. Character used to quote fields.
- line_terminator : The newline character or character sequence to use in the output file.
- chunksize : Rows to write at a time.
- date_format : Format string for datetime objects.
- doublequote : Control quoting of quotechar inside a field.
- escapechar : String of length 1. Character used to escape sep and quotechar when appropriate.
- decimal : Character recognized as decimal separator. E.g. use ‘,’ for European data.
Returns : None or str
示例 1:
# importing the module
import pandas as pd
# creating the DataFrame
my_df = {'Name': ['Rutuja', 'Anuja'],
'ID': [1, 2],
'Age': [20, 19]}
df = pd.DataFrame(my_df)
# displaying the DataFrame
print('DataFrame:\n', df)
# saving the DataFrame as a CSV file
gfg_csv_data = df.to_csv('GfG.csv', index = True)
print('\nCSV String:\n', gfg_csv_data)
输出 :
在执行代码之前:
执行代码后:
我们可以清楚地看到创建的 .csv 文件。
此外,上述代码的输出包括索引,如下所示。
示例 2:转换为没有索引的 CSV 文件。如果我们不希望包含索引,则在index
参数中指定值False
。
# importing the module
import pandas as pd
# creating the DataFrame
my_df = {'Name': ['Rutuja', 'Anuja'],
'ID': [1, 2],
'Age': [20, 19]}
df = pd.DataFrame(my_df)
# displaying the DataFrame
print('DataFrame:\n', df)
# saving the DataFrame as a CSV file
gfg_csv_data = df.to_csv('GfG.csv', index = False)
print('\nCSV String:\n', gfg_csv_data)
输出:
示例 3:转换为没有行标题的 CSV 文件。如果我们不希望包含标头,则在header
参数中分配值False
。
# importing the module
import pandas as pd
# creating the DataFrame
my_df = {'Name': ['Rutuja', 'Anuja'],
'ID': [1, 2],
'Age': [20, 19]}
df = pd.DataFrame(my_df)
# displaying the DataFrame
print('DataFrame:\n', df)
# saving the DataFrame as a CSV file
gfg_csv_data = df.to_csv('GfG.csv', header = False)
print('\nCSV String:\n', gfg_csv_data)
输出:
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。