loc and iloc - part 3

PHOTO EMBED

Thu Nov 25 2021 07:55:27 GMT+0000 (Coordinated Universal Time)

Saved by @Sourabh ##dictionary ##pandas #defining_data_frame #csv #dataframe #square #bracket'

# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Print out drives_right column as Series
print(cars.loc[:, 'drives_right'])
print(cars.iloc[:, 1])

# Print out drives_right column as DataFrame
print(cars.loc[:, ['drives_right']])
print(cars.iloc[:, [1]]) #[] square brackets are very sensitive here


# Print out cars_per_cap and drives_right as DataFrame
print(cars.loc[:, ['drives_right', 'cars_per_cap']])
print(cars.iloc[:, [0,2]]) #[] square brackets are very sensitive here

content_copyCOPY

It's also possible to select only columns with loc and iloc. In both cases, you simply put a slice going from beginning to end in front of the comma: