Tuesday, August 11, 2020

Slicing Columns


Python’s slicing syntax, :, is similar to the range syntax. Instead of a function that specifies start, stop, and step values delimited by a comma, we separate the values with the colon.

If you understand what was going on with the range function earlier, then slicing can be seen as a shorthand means to the same thing.

While the range function can be used to create a generator and converted to a list of values, the colon syntax for slicing only has meaning when slicing and subsetting values, and has no inherent meaning on its own.

small_range = list(range(3))
subset = df.iloc[:, small_range]
print(subset.head())

 

 # slice the first 3 columns
subset = df.iloc[:, :3]
print(subset.head())

 

small_range = list(range(3, 6))
subset = df.iloc[:, small_range]
print(subset.head()) 

 

# slice columns 3 to 5 inclusive
subset = df.iloc[:, 3:6]
print(subset.head())

 

small_range = list(range(0, 6, 2))
subset = df.iloc[:, small_range]
print(subset.head())

# slice every other first 5 columns
subset = df.iloc[:, 0:6:2]
print(subset.head())

 

Try to practice more on your own with some examples as this is a vital concept. In the next post we'll  discuss about Subsetting Rows and Columns

 

 

 

Share:

0 comments:

Post a Comment