Pandas: Export Data to CSV File with No Header


You can use the following syntax to export a pandas DataFrame to a CSV file and not include the header:

df.to_csv('my_data.csv', header=None)

The argument header=None tells pandas not to include the header when exporting the DataFrame to a CSV file.

The following example shows how to use this syntax in practice.

Example: Export Pandas DataFrame to CSV File with No Header

Suppose we have the following pandas DataFrame that contains information about various basketball players:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print(df)

  team  points  assists  rebounds
0    A      18        5        11
1    B      22        7         8
2    C      19        7        10
3    D      14        9         6
4    E      14       12         6
5    F      11        9         5
6    G      20        9         9
7    H      28        4        12

If we use the to_csv() function to export the DataFrame to a CSV file, pandas will include the header row by default:

#export DataFrame to CSV file
df.to_csv('basketball_data.csv')

Here is what the CSV file looks like:

Notice that the header row with the column names is included in the CSV file.

To export the DataFrame to a CSV file without the header, we must specify header=None:

#export DataFrame to CSV file without header
df.to_csv('basketball_data.csv', header=None)

Here is what the CSV file looks like:

Notice that the header row is no longer included in the CSV file.

Note: You can find the complete documentation for the pandas to_csv() function here.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Read CSV Without Headers in Pandas
How to Merge Multiple CSV Files in Pandas
How to Only Read Specific Rows from CSV File in Pandas

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *