How to write Pandas DataFrame as TSV using Python?

A Pandas DataFrame can be written as a Tab-Separated Value (TSV) file using the to_csv() method. TSV is a common format for storing tabular data where columns are separated by tabs instead of commas.

Syntax

df.to_csv(file_path, sep='\t', index=False, header=True)

Parameters

  • file_path: Path and name of the output TSV file

  • sep: Column separator. Use '\t' for tab separation

  • index: Whether to include row indices. Set False to exclude

  • header: Whether to include column names as first row

Basic Example

Here's how to write a DataFrame containing employee data to a TSV file ?

import pandas as pd

# Create a DataFrame
data = {
    'Name': ['John', 'Alice', 'Bob'],
    'Age': [28, 32, 45],
    'Salary': [50000, 60000, 75000]
}
df = pd.DataFrame(data)

# Write DataFrame to TSV file
df.to_csv('employees.tsv', sep='\t', index=False)

print("DataFrame written to employees.tsv successfully")
print(df)
DataFrame written to employees.tsv successfully
    Name  Age  Salary
0   John   28   50000
1  Alice   32   60000
2    Bob   45   75000

Using Custom Column Names

You can specify custom column names in the output TSV file ?

import pandas as pd

# Create a DataFrame
data = {
    'Product': ['A', 'B', 'C'],
    'Units_Sold': [100, 200, 150],
    'Revenue': [5000, 8000, 6000]
}
df = pd.DataFrame(data)

# Custom column names for TSV output
custom_headers = ['Product Name', 'Total Units', 'Total Revenue']

# Write with custom headers
df.to_csv('sales.tsv', sep='\t', index=False, header=custom_headers)

print("DataFrame with custom headers written to sales.tsv")
print(df)
DataFrame with custom headers written to sales.tsv
  Product  Units_Sold  Revenue
0       A         100     5000
1       B         200     8000
2       C         150     6000

Including Row Index

To include row indices in the TSV file, set index=True ?

import pandas as pd

data = {
    'City': ['New York', 'London', 'Tokyo'],
    'Population': [8419000, 8982000, 13960000]
}
df = pd.DataFrame(data)

# Include index in TSV output
df.to_csv('cities.tsv', sep='\t', index=True)

print("DataFrame with index written to cities.tsv")
print(df)
DataFrame with index written to cities.tsv
       City  Population
0  New York     8419000
1    London     8982000
2     Tokyo    13960000

Key Points

  • TSV files use tabs ('\t') as column separators

  • Set index=False to exclude row numbers from output

  • Use header parameter for custom column names

  • TSV format is ideal for data exchange between different systems

Conclusion

Use df.to_csv() with sep='\t' to write DataFrames as TSV files. This method provides flexibility for custom headers and index inclusion based on your requirements.

Updated on: 2026-03-27T15:20:46+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements