w3resource

Pandas DataFrame: Write a DataFrame to CSV file using tab separator


27. Write DataFrame to CSV (Tab Separator)

Write a Pandas program to write a DataFrame to CSV file using tab separator.

Sample data:
Original DataFrame
col1 col2 col3
0 1 4 7
1 4 5 8
2 3 6 9
3 4 7 0
4 5 8 1
Data from new_file.csv file:
col1\tcol2\tcol3
0 1\t4\t7
1 4\t5\t8
2 3\t6\t9
3 4\t7\t0
4 5\t8\t1

Sample Solution:

Python Code :

import pandas as pd
import numpy as np
d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8, 9, 0, 1]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
print('Data from new_file.csv file:')
df.to_csv('new_file.csv', sep='\t', index=False)
new_df = pd.read_csv('new_file.csv')
print(new_df)

Sample Output:

     Original DataFrame
   col1  col2  col3
0     1     4     7
1     4     5     8
2     3     6     9
3     4     7     0
4     5     8     1
Data from new_file.csv file:
  col1\tcol2\tcol3
0          1\t4\t7
1          4\t5\t8
2          3\t6\t9
3          4\t7\t0
4          5\t8\t1             

Explanation:

The above code first creates a Pandas DataFrame ‘df’ from a dictionary ‘d’ containing three columns: col1, col2, and col3.

df.to_csv('new_file.csv', sep='\t', index=False): This code saves this DataFrame as a tab-separated file named new_file.csv using the to_csv() method with the parameters sep='\t' and index=False.

new_df = pd.read_csv('new_file.csv'): This code loads the saved file into a new DataFrame new_df using the read_csv() function.

Finally print() function prints the content of 'new_df' to the console.


For more Practice: Solve these Related Problems:

  • Write a Pandas program to export a DataFrame to a CSV file using a tab as the separator and a custom encoding.
  • Write a Pandas program to write a DataFrame to a CSV file with tab delimiters and without the header row.
  • Write a Pandas program to save a DataFrame to a tab-separated file and then read it back verifying the data integrity.
  • Write a Pandas program to export a DataFrame to CSV with tab separation and include the index as a column in the file.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to add one row in an existing DataFrame.
Next: Write a Pandas program to count city wise number of people from a given of data set (city, name of the person).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.