Write data on CSV format using pandas from DataFrame?


If we want to convert application data into CSV format under data science then we can use to_csv().


df = pd.DataFrame(dict)

# saving the dataframe


Now I am creating dictionary objects to store student records that will be saved into CSV file using data frames.

import pandas as pd

stu = {'rno':[1001,1002,1003],'sname':['stu1','stu2','stu3']}




If we want to write a CSV file without an index or Without a Column Header then we can use the following property.

df = pd.DataFrame(dict)

# saving the dataframe
df.to_csv('file2.csv', header=False, index=False)

Example without header and indexing?

import pandas as pd

stu = {'rno':[1001,1002,1003],'sname':['stu1','stu2','stu3']}



How to read excel files in pandas?

pip install openpyxl.

import pandas as pd

 # Import the excel file and call it xls_file

excel_file = pd.ExcelFile('Test.xlsx')

  # View the excel_file's sheet names


  # Load the excel_file's Sheet1 as a dataframe

df = excel_file.parse('Sheet1')


Post a Comment


POST Answer of Questions and ASK to Doubt

  1. Program to take input as dictionary data and convert it into dataframe and calculating the total and percentage of all students and adding their columns.

    import pandas as pd
    import numpy as np
    mark = {'NAME':['HARISH','PIYUSH','YOGESH','TANISHQ','AYUSH','DEEPAK'],'PHYSICS':[50,60,70,32,45,79],'CHEMISTRY':[44,12,70,60,57,99],'MATHS':[89,88,70,40,78,98]}
    xl = pd.DataFrame(mark)
    supply = []
    total = []
    eligible = []
    percent = []
    #loop for finding the list of students having supplementary
    for i in range(0,len(xl)):
    for j in range(1,len(xl.columns)):
    if xl.iloc[i,j] < 33:
    # print(f'{xl.iloc[i,0]} got supplementary')
    #loop for finding the list of students who are not gettting supplementary
    for a in range(0,len(xl)):
    if xl.iloc[a,0] not in supply:
    #loop for calculating total and percentage list
    for check in range(0,len(xl)):
    if xl.iloc[check,0] not in supply:
    sum = xl['PHYSICS'][check] + xl['CHEMISTRY'][check] + xl['MATHS'][check]
    per = sum/3
    t = pd.Series(total) #converting total list into series
    p = pd.Series(percent) #converting percentage into series
    xl['total'] = t #adding new column named total in csv
    xl['percentage'] = p #adding new column names percenage in csv
    xl.to_csv('student_marksheet.csv') #converting a dataframe into csv with name student_marksheet.csv

Post a Comment