Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 separationindex: Whether to include row indices. Set
Falseto excludeheader: 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 separatorsSet
index=Falseto exclude row numbers from outputUse
headerparameter for custom column namesTSV 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.
