Program to write a DataFrame to a CSV file

In this python pandas program, we will write a DataFrame to a CSV file using the pandas library.

Steps to solve the program
  1. Import pandas library as pd.
  2. Create a dataframe using pd.DataFrame().
  3. Write the dataFrame to a CSV file using a tab separator using df.to_csv(‘new_file.csv’, sep=’\t’, index=False)
  4. Print the output.
				
					import pandas as pd
d = {'Sr.no.':[1,2,3,4],'Name':['Alex','John','Peter','Klaus'],'Age':[30,27,29,33],'Salary':[50000,65000,58000,66000]}
df = pd.DataFrame(d)
df.to_csv('new_file.csv', sep='\t', index=False)
new = pd.read_csv('new_file.csv')
print(new)
				
			

Output :

				
					0  Sr.no.\tName\tAge\tSalary
0        1\tAlex\t30\t50000
1        2\tJohn\t27\t65000
2       3\tPeter\t29\t58000
3       4\tKlaus\t33\t66000
				
			

change the order of columns in a DataFrame

count Country wise population from a given data set

Leave a Comment