لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

Python Data Science Pandas Read CSV Read CSV Files

A CSV files (comma separated files) is a simple way to store big data sets.

CSV files contains plain text and is a well know format that can be read by everyone including Pandas. In the examples below we will be using a CSV files called 'nameoffile.csv'.

How to Read CSV File In Pandas?

Example 1: Load the CSV into a DataFrame.

Code

import pandas as pd

df = pd.read_csv('abalone.csv')

print(df.to_string())

the output will be


Note: use to_string() to print the entire DataFrame.

If you have a large DataFrame with many rows, Pandas will only return the first 5 rows, and the last 5 rows.

Example 2: Print the DataFrame without the to_string() method.

Code

import pandas as pd

df = pd.read_csv('abalone.csv')

print(df)

the output will be


max_rows: The number of rows returned is defined in Pandas option settings.

You can check your system's maximum rows with the pd.options.display.max
_rows statement.

Example 3: Check the number of maximum returned rows.

import pandas as pd

print(pd.options.display.max
_rows)

the output will be

60

In the system that is being used now the number is 60, which means that if the DataFrame contains more than 60 rows, the print(df) statement will return only the headers and the first and last 5 rows.

You can change the maximum rows number with the same statement.

Example 4: Increase the maximum number of rows to display the first and last 5 rows.

Code

import pandas as pd

pd.options.display.max_rows = 60

df = pd.read_csv('data.csv')

print(df)
the output will be


In order to see the complete dataset set the value to 9999 in the 2nd line of code above see the code below. Increase the maximum number of rows to display the entire DataFrame.

Code

import pandas as pd

pd.options.display.max
_rows = 9999

df = pd.read_csv('data.csv')

print(df)

the output will be

the whole dataset

df. head() and tail()

If you want you can use either head() or tail() method to read the specified no of rows as per your selection either starting from head or tail as the case may be.

Example 5 Use the head method to read the first 10 rows.

Code

import pandas as pd

df = pd.read_csv

print(df.head(10))

the output will be


Example 7 Use the tail method to read the last 10 rows.

Code

import pandas as pd

df = pd.read_csv('abalone.csv')

print(df.tail(10))

the output will be


Example 8 You can even load a python dictionary like below.

Code

import pandas as pd

import numpy as np

LGI = {

'Low GI Diet Fruits':["Apple","Apricots","Apple",
"Bananas","Grapes","Bananas",
"Mangoes","Orangs",
"Mangoes","Pineapple"],

'Weight (Gms)' :[120,60,120,120,
120,120,120,120,120,120],

'GI Scores':[40,32,40,47,43,47,51,48,51,51]

}

df = pd.DataFrame(LGI)

print(df)

the output will be