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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With