1

If I slice a pandas dataframe with dataset.iloc[:, 1:2].values, it's giving me a 2 dimensional(matrix) structured data where dataset.iloc[:, 1].values is giving me 1 dimensional data. So, my doubt is iloc[:,1:2] & iloc[:,1] dont do the same thing ?

Here is the sample code:

    >>> df1 = df.iloc[:, 1:2].values
    >>> print(df1.shape,df1.ndim)
    (9578, 1) 2
    >>> df2 = df.iloc[:, 1].values
    >>> print(df2.shape,df2.ndim)
    (9578,) 1
    >>>
Soumen Das
  • 31
  • 1
  • 7
  • 1
    Since you're getting different results, it's pretty safe to say they don't do the same thing. – AKX Jul 07 '19 at 19:51
  • 1
    `.iloc[:,1]` returns series while `.iloc[:,1:2]` returns dataframe. It is the same as `df['A']` returns series while `df[['A']]` returns dataframe – Andy L. Jul 07 '19 at 19:53

4 Answers4

4

df.iloc[:, 1:2] returns a dataframe (matrix) whereas df.iloc[:, 1] returns a series (vector). A vector does not have column size. Try this if you want to keep the dataframe structure

df.iloc[:,[1]]
Mark Wang
  • 2,623
  • 7
  • 15
2

Technically speaking slicing method you are using is called 'Selection by Position'. iloc is termed as integer based location.

When you use df.iloc[:, 1:2] resulting output would be a pandas DataFrame object:

>>> type(df.iloc[:, 1:2])
pandas.core.frame.DataFrame

When you use df.iloc[:, 1] resulting output would be a pandas Series object:

>>> type(df.iloc[:, 1])
pandas.core.series.Series

Knowing the difference is critical because each object has different methods that may not work on other object.

0

Yes, iloc[:,1:2] & iloc[:,1] these are not similar as one is giving Dataframe and other one is giving Serious as an output.

Using df.iloc[:,1:2] gives Dataframe and it give in 2-d as Dataframe is an 2-d data structure

type(df.iloc[:, 1:2])
pandas.core.frame.DataFrame

Using df.iloc[:,1] gives Series and Series is an 1-d labeled array

type(df.iloc[:, 1])
pandas.core.series.Series
ankur singh
  • 72
  • 1
  • 7
0

Pandas iloc() is actually doing what you should expect in a Python context. Compare the following.

>>> numbers = [0, 1, 2]
>>> numbers[1]
1
>>> numbers[1:2]
[1]

The former gives 0-dimensional data and the latter 1-dimensional data which is analogous to your example.

ulmefors
  • 516
  • 3
  • 11