Pandas | 16 ways to read csv file with read_csv




To read a csv file in pandas, we simply use 
pd.read_csv('data.csv')

Here are 16 ways to read the csv files with different options.

1 - Read CSV file with header
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv")

2 - Read CSV file without header
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", header = None)

3 - Read CSV file without header add column names
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", names=["ID", "FN", "LN"])

4 - Read CSV file with header add column names
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", skiprows = 1,names=["ID", "FN", "LN"])

5 - Read csv files only specific columns
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", usecols=['First Name', 'LastName'])

6 - Read csv by column index
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", usecols=[1,2])

7 - Read csv files without index
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", index_col=None)

df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", index_col=False)

8 - Read csv change column data types
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", dtype = {'CustomerID': 'float32'})

9 - Read csv first col as index
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", index_col=0)

10 - Read csv missing values
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", na_values=['1.0'])

11 - Read csv remove last 2 rows
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", engine='python',skipfooter=2)

12 - Read csv skip rows
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", skiprows = 2)
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", skiprows = [1,2])
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", skiprows = range(1,3))

13 - Read csv pipe delimited
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", sep='|')

14 - Read csv use second row as header
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", header=1)

15 - Read first n rows
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv", nrows = 3)

16- Read csv all columns as string
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv",dtype = str)

17 - Read csv all except few columns as string
df = pd.read_csv(r"C:\Users\HP\Documents\Python\TestFiles\Customers.csv",dtype = 'float64' , converters = {'First Name': str, 'LastName': str})


Post a Comment

Previous Post Next Post

Contact Form