YouTip LogoYouTip

Pandas Df To Csv

[![Image 1: Python Common Functions](#) Pandas Common Functions](#) * * * `to_csv()` is a method of DataFrame that is used to export data as a CSV (Comma Separated Values) file. CSV is one of the most commonly used data export formats. It stores tabular data in plain text form, has strong compatibility, and can be read by almost all data analysis tools. `to_csv()` is feature-rich, supporting custom separators, encoding methods, index processing and other options to meet various export needs. * * * ## Basic Syntax and Parameters ### Syntax Format 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, quoting=None, quotechar='"', line_terminator=None, chunksize=None, date_format=None, doublequote=True, escapechar=None, ...) ### Parameter Description | Parameter | Type | Description | Default Value | | --- | --- | --- | --- | | path_or_buf | str, path object, file-like object | File path, returns string if None | None | | sep | str | Field separator | ',' | | na_rep | str | Missing value representation | '' | | float_format | str | Float number format | None | | columns | list | Specify columns to export | None | | header | bool, list | Whether to export column names | True | | index | bool | Whether to export index | True | | index_label | str | Index column name | None | | mode | str | Write mode: 'w' overwrite, 'a' append | 'w' | | encoding | str | File encoding | None | ### Return Value * **Return Type**: `None` or `str` * When a file path is specified, it writes to the file and returns None. * When `path_or_buf=None`, it returns a CSV-formatted string. * * * ## Examples Through the following examples, master the various usages of `to_csv()`. ### Example 1: Basic Usage - Export to CSV File First create a DataFrame, then use `to_csv()` to export to a CSV file. ## Example import pandas as pd # Create a sample DataFrame data ={ 'name': ['Tom','Jerry','Mike','Lucy'], 'age': [28,35,42,26], 'city': ['Beijing','Shanghai','Guangzhou','Shenzhen'], 'salary': [8000,12000,15000,7000] } df = pd.DataFrame(data) # Example 1a: Most basic export # path_or_buf: file path (the required parameter is file path, here set to None to return string) csv_string = df.to_csv()# No path specified, returns string print("Returned CSV string:") print(csv_string) print() # Export to file # By default includes index and column names df.to_csv('output_basic.csv', index=False)# index=False does not export index print("Exported to output_basic.csv") # Read and verify df_check = pd.read_csv('output_basic.csv') print("nVerification read:") print(df_check) **Expected Output:** Returned CSV string:,name,age,city,salary 0,Tom,28,Beijing,80001,Jerry,35,Shanghai,120002,Mike,42,Guangzhou,150003,Lucy,26,Shenzhen,7000Exported to output_basic.csv Verification read: name age city salary 0 Tom 28 Beijing 80001 Jerry 35 Shanghai 120002 Save Mike 42 Guangzhou 150003 Lucy 26 Shenzhen 7000 **Code Analysis:** * `to_csv()` exports index (first column without column name) and column names by default. * Setting `index=False` can skip the index, making it more convenient when importing. * When no path is specified, it returns a CSV-formatted string. ### Example 2: Custom Separator and Format CSV files can use different separators, and you can also customize the format of numbers and missing values. ## Example import pandas as pd # Create DataFrame with missing values and floats data ={ 'name': ['Tom','Jerry','Mike','Lucy'], 'age': [28,35,42,None],# Missing value 'score': [85.5,92.3,78.9,95.0], 'city': ['Beijing','Shanghai',None,'Shenzhen'] } df = pd.DataFrame(data) # Example 2a: Use semicolon separator df.to_csv('output_semicolon.csv', sep=';', index=False) print("Export with semicolon separator:") with open('output_semicolon.csv','r')as f: print(f.read()) print() # Example 2b: Custom missing value representation df.to_csv('output_na.csv', index=False, na_rep='N/A') print("Custom missing value representation:") with open('output_na.csv','r')as f: print(f.read()) print() # Example 2c: Format float numbers # float_format uses Python formatting string df.to_csv('output_float.csv', index=False, float_format='%.2f') print("Formatted float numbers:") with open('output_float.csv','r')as f: print(f.read()) print() # Example 2d: Export partial columns df.to_csv('output_columns.csv', index=False, columns=['name','score']) print("Export specified columns:") with open('output_columns.csv','r')as f: print(f.read()) **Expected Output:** Export with semicolon separator: name;age;score;city Tom;28;85.5;BeijingJerry;35;92.3;ShanghaiMike;42;78.9;GuangzhouLucy;;95;ShenzhenCustom missing value representation: name,age,score,city Tom,28,85.5,BeijingJerry,35,92.3,ShanghaiMike,42,78.9,GuangzhouLucy,N/A,95.0,N/A Formatted float numbers: name,age,score,ccolumnTom,28,85.50,BeijingJerry,35,92.30,
← Pandas Df To JsonPandas Pd Read Html β†’