Slicing Pandas DataFrames is a powerful technique, allowing extraction of specific data subsets based on integer positions. In this article, let’s understand examples showcasing row and column slicing, cell selection, and boolean conditions.
Slicing Pandas Dataframe
With the help of Pandas, we can perform slicing in Dataframe. Slicing in pandas dataframes using iloc[] is a powerful technique in Python for extracting specific subsets of data. The iloc[] method allows you to locate and extract rows and columns based on their integer positions.
To perform slicing with iloc[] , you specify the row and column indices you want to include in your sliced dataframe. The syntax is similar to traditional array slicing, making it intuitive for Python users. For example, df.iloc[1:5, 2:4] extracts rows 2 to 5 and columns 3 to 4 from the dataframe.
Slicing a DataFrame in Pandas includes the following steps:
- Create a DataFrame
- Slice the DataFrame
Let’s import pandas library , and create pandas dataframe from custom nested list.
Python
import pandas as pd
# Initializing the nested list with Data set
player_list = [['M.S.Dhoni', 36, 75, 5428000],
['A.B.D Villers', 38, 74, 3428000],
['V.Kohli', 31, 70, 8428000],
['S.Smith', 34, 80, 4428000],
['C.Gayle', 40, 100, 4528000],
['J.Root', 33, 72, 7028000],
['K.Peterson', 42, 85, 2528000]]
# creating a pandas dataframe
df = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary'])
df # data frame before slicing
Output:
Name Age Weight Salary
0 M.S.Dhoni 36 75 5428000
1 A.B.D Villers 38 74 3428000
2 V.Kohli 31 70 8428000
3 S.Smith 34 80 4428000
4 C.Gayle 40 100 4528000
5 J.Root 33 72 7028000
6 K.Peterson 42 85 2528000
1. Slicing Using iloc
A. Slicing Rows in dataframe in python
Python
# Slicing rows in data frame
df1 = df.iloc[0:4]
# data frame after slicing
df1
Output:
Name Age Weight Salary
0 M.S.Dhoni 36 75 5428000
1 A.B.D Villers 38 74 3428000
2 V.Kohli 31 70 8428000
3 S.Smith 34 80 4428000
In the above example, we sliced the rows from the data frame.
B. Slicing Columns in dataframe in python
Python
# Slicing columnss in data frame
df1 = df.iloc[:, 0:2]
# data frame after slicing
df1
Output:
Name Age
0 M.S.Dhoni 36
1 A.B.D Villers 38
2 V.Kohli 31
3 S.Smith 34
4 C.Gayle 40
5 J.Root 33
6 K.Peterson 42
In the above example, we sliced the columns from the data frame.
C. Selecting a Specific Cell in Dataframe in Python
Python
specific_cell_value = df.iloc[2, 3] # Row 2, Column 3 (Salary)
print("Specific Cell Value:", specific_cell_value)
Output:
Specific Cell Value: 8428000
D. Using Boolean Conditions in Dataframe in Python
Python
filtered_data = df[df['Age'] > 35].iloc[:, :] # Select rows where Age is greater than 35
print("\nFiltered Data based on Age > 35:\n", filtered_data)
Output:
Filtered Data based on Age > 35:
Name Age Weight Salary
0 M.S.Dhoni 36 75 5428000
1 A.B.D Villers 38 74 3428000
4 C.Gayle 40 100 4528000
6 K.Peterson 42 85 2528000
2. Slicing Using loc[]
We can also, implement slicing through loc there are some limitations:
loc relies on labels, and if your DataFrame has custom labels, you need to be careful with how you specify them. - If labels are integers, there might be confusion between using integer positions and actual labels.
For this, we need to set index as labels manually with following code:
Python
df_custom = df.set_index('Name')
df_custom
Output:
Age Weight Salary
Name
M.S.Dhoni 36 75 5428000
A.B.D Villers 38 74 3428000
V.Kohli 31 70 8428000
S.Smith 34 80 4428000
C.Gayle 40 100 4528000
J.Root 33 72 7028000
K.Peterson 42 85 2528000
A. Slicing Rows in Dataframe in Python
Python
sliced_rows_custom = df_custom.loc['A.B.D Villers':'S.Smith']
sliced_rows_custom
Output:
Age Weight Salary
Name
A.B.D Villers 38 74 3428000
V.Kohli 31 70 8428000
S.Smith 34 80 4428000
B. Selecting Specified cell in Dataframe in Python
Python
specific_cell_value = df_custom.loc['V.Kohli', 'Salary']
print("\nValue of the Specific Cell (V.Kohli, Salary):", specific_cell_value)
Output:
Value of the Specific Cell (V.Kohli, Salary): 8428000
Conclusion
In summary, both iloc[] and loc[]provide versatile slicing capabilities in Pandas. While iloc[] is integer-based, loc[] relies on labels, requiring careful consideration when working with custom indices or mixed data types.
Slicing Pandas DataFrame- FAQs
What is the slice method in pandas?
The slice() method in Pandas offers several options to manipulate string columns. For instance, you can extract a substring within specified start and stop indices using str.slice(start, stop).
How do I cut down a DataFrame in pandas?
Use iloc or loc in Pandas to extract specific rows, columns, or cells efficiently.
Similar Reads
Slicing Pandas Dataframe
Slicing Pandas DataFrames is a powerful technique, allowing extraction of specific data subsets based on integer positions. In this article, let's understand examples showcasing row and column slicing, cell selection, and boolean conditions. Slicing Pandas Dataframe With the help of Pandas, we can p
4 min read
Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal comp
12 min read
Split Pandas Dataframe by Rows
In this article, we will explore the process of Split Pandas Dataframe by Rows. The Pandas DataFrame serves as the focal point, and throughout this discussion, we will experiment with various methods to Split Pandas Dataframe by Rows. Split Pandas DataFrame by Rows In this article, we will elucidate
3 min read
Python | Pandas DataFrame.ix[ ]
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DataFrame.ix[ ] is both Label and Integer based slicing technique. Besides pure
2 min read
Python | Pandas dataframe.div()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.div() is used to find the floating division of the dataframe and other
3 min read
Python | Pandas dataframe.slice_shift()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.slice_shift() function is Equivalent to shift without copying data. T
3 min read
Python | Pandas dataframe.melt()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.melt() function unpivots a DataFrame from wide format to long format,
2 min read
Python | Pandas dataframe.clip()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.clip() is used to trim values at specified input threshold. We can us
3 min read
Python | Pandas dataframe.mask()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.mask() function return an object of same shape as self and whose corr
3 min read
Python | Pandas dataframe.rdiv()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.rdiv() function compute Floating division of dataframe and other, ele
2 min read