Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between cars.iloc[[3, 0]], cars.iloc[[3],[0]] and cars.iloc[3, 0]

I am studying pandas and working on cars(a csv file). I ran the below commands:

1) cars.iloc[[3, 0]]

Out[2]: 
cars_per_cap        country drives_right

IN 18 India False US 809 United States True

2) cars.iloc[[3],[0]]

Out[7]: 
cars_per_cap

IN 18

3) cars.iloc[3, 0]

Out[9]: 18

I am getting confused in the 1st and 3rd command, I checked the type of all and the first 2 are the DataFrame and the 3rd one is not. However, why am I getting a different output for 1st and 3rd? Any help would be appreciated.

like image 901
sra7687 Avatar asked Mar 07 '23 15:03

sra7687


1 Answers

df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'F':list('aaabbb')}, index=range(10, 16))

print (df)
    A  B  C  D  E  F
10  a  4  7  1  5  a
11  b  5  8  3  3  a
12  c  4  9  5  6  a
13  d  5  4  7  9  b
14  e  5  2  1  2  b
15  f  4  3  0  4  b

Select 3. and 0. rows, all columns:

print (df.iloc[[3,0]])
#same as 
#print (df.iloc[[3,0], :])
    A  B  C  D  E  F
13  d  5  4  7  9  b
10  a  4  7  1  5  a

Select 3. and 0. columns, all rows:

print (df.iloc[:, [3,0]])

    D  A
10  1  a
11  3  b
12  5  c
13  7  d
14  1  e
15  0  f

Select 3. row and 0. columns - nested list create one item Series

print (df.iloc[[3],[0]])
    A
13  d

Same as above, only without nested lists get scalar:

print (df.iloc[3,0])
d

Another selecting:

Select 3. and 0. row, 0. column - second [] create one column DataFrame:

print (df.iloc[[3, 0],[0]])
    A
13  d
10  a

... and if omit it get Series:

print (df.iloc[[3, 0], 0])
13    d
10    a
Name: A, dtype: object

If want select one row and multiple columns:

print (df.iloc[[0], [3, 0]])
    D  A
10  1  a

print (df.iloc[0, [3, 0]])
D    1
A    a
Name: 10, dtype: object

And last for seelct multiple rows and multiple columns:

print (df.iloc[[3,0], [3,0]])
    D  A
13  7  d
10  1  a
like image 72
jezrael Avatar answered Apr 12 '23 10:04

jezrael