w3resource

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

Pandas: DataFrame Exercise-27 with Solution

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.

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.