Search code examples
pythonpandas

Parameter problems of iloc() functions in pandas


I just started to learn pandas, and the call of df.iloc[[1][0]] (df is the pd.DataFrame data type with a shape of (60935, 54)) appeared in a code. Understanding df.iloc[[1 ][0]] should be a line of df, but how should we understand [[1][0]]? Why do the parameters in iloc[] allow the acceptance of two adjacent lists? How to deal with the inside of iloc[]? This is obviously not an index of rows and columns. In addition, I found that when the second number is not 0 or -1, there will be an index out-of-bounds error. Why is this?

mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000}]
df = pd.DataFrame(mydict)
print(df.iloc[[0][-1]].shape)
    output(4,)
print(df.iloc[[0][0]].shape)
    output(4,)
print(df.iloc[[0]].shape)
    output(1, 4)
print(df.iloc[[0][1]].shape)
    outputIndexError: list index out of range
print(type(df.iloc[[0]]))
    output<class 'pandas.core.frame.DataFrame'>
print(type(df.iloc[[0][0]]))
    output<class 'pandas.core.series.Series'

Solution

  • You misunderstood the syntax [0][-1] an so on.

    [0] is a list of length 1 containing the number 0
    [1] is still al list of length 1 containing the number 1

    [0][-1] means: "take the last element of the list [0]", which is equivalent to .iloc[0]

    [1][0] means: "take the first element of the list [1]", which is equivalent to .iloc[1]

    [0][1] means: "take the second element of the list [0], which does not exist because the list [0] does not have a second element.

    The error you get is not coming from .iloc, it is coming from the wrong list indexing [0][1].