Dataframe Slicing
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
Related Resources:
- Create Dataframe from Dictionary Create dataframe from dictionary Use “DataFrame” method of pandas library to create dataframe from dictionary # Imports import pandas as...
- Loop through rows in pandas | Iterate over rows Loop through rows in Pandas Use “iterrows” method of pandas dataframe to loop through rows # Imports import pandas as...
- Delete rows based on column value Delete rows based on column value Use pandas dataframe’s inbuilt filter to delete rows based on column value # Imports...
- 8 Ways to Drop Columns in Pandas | A Detailed Guide 8 Ways to Drop Columns in Pandas Often there is a need to modify a pandas dataframe to remove unnecessary...
- Save pandas dataframe to csv or excel file ( 2 Ways to Save pandas dataframe) Save Pandas dataframe to csv and excel file Use “to_csv” and “to_excel” methods to save pandas dataframe to csv and...
- Rename columns in Pandas | Change column Names Rename Columns in Pandas Set df.columns = List of column name strings to rename columns # Imports import pandas as...
- Reset Index in Pandas Dataframe | Pandas tutorial Reset Index Reset index in pandas using “reset_index” method of pandas dataframe. When we perform slicing or filtering operations on...
- Not Operation in Pandas Conditions | Pandas tutorial Not Operation in Pandas Conditions Apply not operation in pandas conditions using (~ | tilde) operator. In this Pandas tutorial...
- Sort Dictionary by Value Sort Dictionary by Value “Key” parameter of sorted function can be used to sort by value. # Let's create a...
- Pandas series from Dictionary | Pandas Tutorial Pandas Series from Dictionary Create pandas series from dictionary using “Series” method of Pandas library. In the below example we...