How to Set Dependent Variables and Independent Variables (iloc example) in Python

with 2 Comments

 

Say you have imported your CSV data into python as “Dataset”, and you want to split dependent variables and the independent variables. You can use the iloc function.

iloc[row , column]

If you want to include all of the row or column, simply type “:”   , and you should always remember the “,” within the bracket.

iloc Example 1

dataset=pd.read_csv(“data.csv”)

X= dataset.iloc[ : , :-1].values

y= dataset.iloc[ : , 4].values

 

This declares dataset as your csv data.

For dependent variable X, it takes all the rows in the dataset and it takes all the columns up to the one before the last column.

For independent variable Y, it takes all the rows, but only column 4 from the dataset.

 

iloc example1

iloc Example 2

dataset=pd.read_csv(“data.csv”)

X= dataset.iloc[ 1:2 , :-1].values

 

Notice how it takes rows begin at row 1 and end before row 2

While it takes all the column until the one before the last column.

iloc -example 2

iloc Example 3 – Multiple of Separated Columns

dataset=pd.read_csv(“data.csv”)

X= dataset.iloc[1: , 1:-1].values
y= dataset.iloc[: , [0,4]].values

For X, we will take the rows starting from row 1 til the last row of the dataset; and we are only going to take from column 1 til column 3 ( or the one before the last)

For y, we are going to take multiple columns. Y is a combination of column 0 and column 4.

If you do  y= dataset.iloc[: , 0].values, it will only take column 0.

If you do y= dataset.iloc[: , [0,4]].values, it will take column 0 plus column 4.

Notice that [0,4] is an array of index.

iloc example 3

 

iloc Example 4 – Multiple of Separated Columns

dataset=pd.read_csv(“data.csv”)
y= dataset.iloc[: , [0,2,4]].values

Y is going to be a combination of multiple of separated columns.

Just like the previous example, we will use array for the column section. (ie: [0,2,4]).

 

 

iloc -example 4

 

Other Sections on Data Handling in Python

1.) How to Import Libraries 

2.) How to Know and Change the Working Directory 

3.) How to Import CSV Data using Pandas

4.) How to Set Dependent Variables and Independent Variables using iloc

5.) How to Handle Missing data with Imputer

6.) How to Set Categorical Data (Dummy Variable) using LabelEncoder and OneHotEncoder

7.) How to Split Data into Training Set and Testing Set

8.) How to Apply Feature Scaling

2 Responses

  1. Thanks regarding supplying such very good details.

  2. gadget Cover insurance
    | Reply

    Some terrific images. Fantastic shades.

Leave a Reply