Browsing Tag



Pandas – Tips and Tricks – df.loc, df.iloc

This notebook is a part of Pandas – Tips and Tricks mini-series, focusing on different aspects of pandas library in Python. In the below examples we will be looking at selecting the data by using .loc and .iloc methods. The notebook is also available on GitHub.

.loc: is primarily label based indexing.

.iloc: is primarily integer position based indexing.

Previous blog posts on the topic: Data import with Python, using pandas DataFrame – Part 1


Let’s start by importing pandas and loading the data:

In [1]:
# Loading the library
import pandas as pd

# I am using the data from WHO as an example
df = pd.read_csv('Data/SuicBoth.csv')

# Checking the DataFrame shape

# Checking the imported data
(183, 6)

String, String Methods, and String Manipulation

String is a collection of characters. Any character can be accessed by its index. The indexing of a string starts at 0 (or -1 if it’s indexed from the end). We can get the number of characters in a string by using built-in function len. Compared to the indexing, len is not zero based.

In [1]:
# Creating a string
text = 'Some collection of words'

# Assigning the number of characters in the given string to a variable
total_char = len(text)

# Printing the total number of characters
print('Number of characters = {}'.format(total_char))
Number of characters = 24