Header Ads Widget

Responsive Advertisement

How to read and write csv file using python.


Important code related to how read comma Separated Values, which having .csv file extention. in this article we will discuss all the function related to CSV file 

python


import pandas as pd

df= pd.read_csv("C:\\Users\\YOGENDRASINGH\\Downloads\\transactions.csv")

#C:\\Users\\YOGENDRASINGH\\Downloads\\transactions.csv == file path name with extention where your .csv file stored


print(df.shape)

#df= pd.read_csv("C:\\Users\\YOGENDRASINGH\\Downloads\\transactions.csv",usecols=['Name','Com'])

df= pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\transactions.csv", nrows=5)

#nrows show 5 records from the file


df= pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\transactions.csv", nrows=5,header=None)



print(df)

df= pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\transactions.csv", nrows=5,header=None, index_col=0)

print(df)

df= pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\transactions.csv", nrows=5,header=None, index_col=0,skiprows=1)

print(df)

df= pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\transactions.csv", nrows=5,header=None, index_col=0,skiprows=2)

print(df)


df= pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\transactions.csv", nrows=5, index_col=0,skiprows=2, names=['Cam','Income','Paid/Not Paid','Sale_date','Sale_amount'])

print(df)

df= pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\transactions.csv", na_values=[499],nrows=5, index_col=0,skiprows=2, names=['Cam','Income','Paid/Not Paid','Sale_date','Sale_amount'])

print(df)



#how to write and csv file using pandas

# copy file to another file


df= pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\transactions.csv")

df.to_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\Cuelinks_transactions.csv")


#create new file


student={"Roll_No": [1,2],

         "Student_name": ["Rahul","sonu"]}

df1=pd.DataFrame(student,columns=["Roll_No","Student_name"])

#df1.to_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\Newfile1111.csv")

df11=pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\Newfile1111.csv")

print(df11)

df11=pd.read_csv("C:\\Users\\YOGENDRA SINGH\\Downloads\\Newfile1111.csv",index_col=0)

print(df11)

df2=df.mode(axis=0)

print(df2)


Post a Comment

0 Comments