Read CSV Files Using Pandas Library
Read CSV Files Using Pandas Library
2 Importing Libraries
[1]: import numpy as np
import pandas as pd
3 Importing datasets
We use pandas.read_csv() function to read the csv file. In the bracket, we put the file path along
with a quotation mark, so that pandas will read the file into a data frame from that address. The
file path can be either an URL or your local file address.
Name of Dataset is “dataset_1.data”
[ ]: headers_data =␣
↪["symboling","normalized-losses","make","fuel-type","aspiration",␣
↪"num-of-doors","body-style",
"drive-wheels","engine-location","wheel-base",␣
↪"length","width","height","curb-weight","engine-type",
"num-of-cylinders",␣
↪"engine-size","fuel-system","bore","stroke","compression-ratio","horsepower",
"peak-rpm","city-mpg","highway-mpg","price"]
print("headers\n", type(headers_data))
headers
<class 'list'>
1
[ ]: symboling normalized-losses make fuel-type aspiration \
0 3 ? alfa-romero gas std
1 3 ? alfa-romero gas std
2 1 ? alfa-romero gas std
3 2 164 audi gas std
4 2 164 audi gas std
.. … … … … …
200 -1 95 volvo gas std
201 -1 95 volvo gas turbo
202 -1 95 volvo gas std
203 -1 95 volvo diesel turbo
204 -1 95 volvo gas turbo
2
201 5300 19 25 19045
202 5500 18 23 21485
203 4800 26 27 22470
204 5400 19 25 22625
After reading the dataset, we can use the dataframe.head(n) method to check the top n rows of
the dataframe; where n is an integer. Contrary to dataframe.head(n), dataframe.tail(n) will show
you the bottom n rows of the dataframe.
[ ]: # show the first 5 rows using dataframe.head() method
df.head(15)
3
engine-size fuel-system bore stroke compression-ratio horsepower \
0 130 mpfi 3.47 2.68 9.0 111
1 130 mpfi 3.47 2.68 9.0 111
2 152 mpfi 2.68 3.47 9.0 154
3 109 mpfi 3.19 3.40 10.0 102
4 136 mpfi 3.19 3.40 8.0 115
5 136 mpfi 3.19 3.40 8.5 110
6 136 mpfi 3.19 3.40 8.5 110
7 136 mpfi 3.19 3.40 8.5 110
8 131 mpfi 3.13 3.40 8.3 140
9 131 mpfi 3.13 3.40 7.0 160
10 108 mpfi 3.50 2.80 8.8 101
11 108 mpfi 3.50 2.80 8.8 101
12 164 mpfi 3.31 3.19 9.0 121
13 164 mpfi 3.31 3.19 9.0 121
14 164 mpfi 3.31 3.19 9.0 121
4
201 -1 95 volvo gas turbo four
202 -1 95 volvo gas std four
203 -1 95 volvo diesel turbo four
204 -1 95 volvo gas turbo four
5
Data Types
Data has a variety of types. The main types stored in Pandas dataframes are object, float, int, bool
and datetime64. In order to better learn about each attribute, it is always good for us to know the
data type of each column. In Pandas:
Syntax : dataframe.dtypes
returns a Series with the data type of each column.
[ ]: # check the data type of data frame "df" by .dtypes
df.dtypes
[ ]: symboling int64
normalized-losses object
make object
fuel-type object
aspiration object
num-of-doors object
body-style object
drive-wheels object
engine-location object
wheel-base float64
length float64
width float64
height float64
curb-weight int64
engine-type object
num-of-cylinders object
engine-size int64
fuel-system object
bore object
stroke object
compression-ratio float64
horsepower object
peak-rpm object
city-mpg int64
highway-mpg int64
price object
dtype: object
As a result, as shown above, it is clear to see that the data type of “symboling” and “curb-weight”
are int64, “normalized-losses” is object, and “wheel-base” is float64, etc.
These data types can be changed; we will learn how to accomplish this in a later module.
Describe
If we would like to get a statistical summary of each column, such as count, column mean value,
column standard deviation, etc. We use the describe method: Syntax : dataframe.describe() This
method will provide various summary statistics, excluding NaN (Not a Number) values.
6
[ ]: df.describe()
This shows the statistical summary of all numeric-typed (int, float) columns. For example, the
attribute “symboling” has 205 counts, the mean value of this column is 0.83, the standard deviation
is 1.25, the minimum value is -2, 25th percentile is 0, 50th percentile is 1, 75th percentile is 2, and
the maximum value is 3. However, what if we would also like to check all the columns including
those that are of type object.
You can add an argument include = “all” inside the bracket. Let’s try it again.
[ ]: # describe all the columns in "df"
df.describe(include = "all")
7
unique 3 5 3 2 NaN …
top four sedan fwd front NaN …
freq 114 96 120 202 NaN …
mean NaN NaN NaN NaN 98.756585 …
std NaN NaN NaN NaN 6.021776 …
min NaN NaN NaN NaN 86.600000 …
25% NaN NaN NaN NaN 94.500000 …
50% NaN NaN NaN NaN 97.000000 …
75% NaN NaN NaN NaN 102.400000 …
max NaN NaN NaN NaN 120.900000 …
Now, it provides the statistical summary of all the columns, including object-typed attributes. We
can now see how many unique values, which is the top value and the frequency of top value in
the object-typed columns. Some values in the table above show as “NaN”, this is because those
numbers are not available regarding a particular column type.
[ ]: #Replacing "?" with np.nan so that pandas can recognize the null values.
df.replace('?', np.nan, inplace=True)
We use the replace method to replace all occurrences of “?” with np.nan in the DataFrame. The
8
inplace=True argument ensures that the changes are made in place in the original DataFrame.bold
text
Info
Another method you can use to check your dataset is: Syntax : dataframe.info() It provide a
concise summary of your DataFrame.
This method prints information about a DataFrame including the index dtype and columns, non-
null values and memory usage.
[ ]: # look at the info of "df"
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 205 entries, 0 to 204
Data columns (total 26 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 symboling 205 non-null int64
1 normalized-losses 164 non-null object
2 make 205 non-null object
3 fuel-type 205 non-null object
4 aspiration 205 non-null object
5 num-of-doors 203 non-null object
6 body-style 205 non-null object
7 drive-wheels 205 non-null object
8 engine-location 205 non-null object
9 wheel-base 205 non-null float64
10 length 205 non-null float64
11 width 205 non-null float64
12 height 205 non-null float64
13 curb-weight 205 non-null int64
14 engine-type 205 non-null object
15 num-of-cylinders 205 non-null object
16 engine-size 205 non-null int64
17 fuel-system 205 non-null object
18 bore 201 non-null object
19 stroke 201 non-null object
20 compression-ratio 205 non-null float64
21 horsepower 203 non-null object
22 peak-rpm 203 non-null object
23 city-mpg 205 non-null int64
24 highway-mpg 205 non-null int64
25 price 201 non-null object
dtypes: float64(5), int64(5), object(16)
memory usage: 41.8+ KB
Save Dataset
9
Correspondingly, Pandas enables us to save the dataset to csv by using the dataframe.to_csv()
method, you can add the file path and name along with quotation marks in the brackets.
For example, if you would save the dataframe df as automobile.csv to your local machine, you may
use the syntax below:
We can also read and save other file formats, we can use similar functions to pd.read_csv() and
df.to_csv() for other data formats, the functions are listed in the following table:
Read/Save Other Data Formats
10