• Pandas Datafrane slicing is one of the most important operations.

  • Here’s how to do slicing in a pandas dataframe. Often, we are in need to select specific information from a dataframe and slicing let’s us fetch necessary rows, columns etc. In the below tutorial we select specific rows and columns as per our requirement. 

# Imports 
import pandas as pd

# Let's create a pandas dataframe
df = pd.DataFrame({"Name": ['Joyce', 'Joy', 'Ram', 'Maria'], 
                   "Age": [19, 18, 20, 19]}, columns = ['Name', 'Age'])

print("Created dataframe: \n{}".format(df))
Created dataframe: 
    Name  Age
0  Joyce   19
1    Joy   18
2    Ram   20
3  Maria   19
# Let's select those who have age 19
df_age19 = df[df.Age == 19]

print("Selected entries: \n{}".format(df_age19))
Selected entries: 
    Name  Age
0  Joyce   19
3  Maria   19
# Let's select only the name column
df_name = df['Name']

print("Selected entries: \n{}".format(df_name))
Selected entries: 
0    Joyce
1      Joy
2      Ram
3    Maria
Name: Name, dtype: object