2️⃣ 🧱 Pandas Core Data Structures
Estimated reading: 3 minutes 36 views

✂️🔧 Pandas Slicing and Modifying DataFrames – Extract & Update Data Efficiently


🧲 Introduction – Why Slice and Modify DataFrames?

Slicing and modifying DataFrames are essential skills for real-world data processing. Whether you’re extracting specific rows and columns, updating values, or reshaping data, Pandas gives you intuitive tools for fast, accurate transformations.

🎯 In this guide, you’ll learn:

  • How to slice rows and columns using .loc[], .iloc[], and slicing syntax
  • Modify cell values, columns, and rows
  • Add or delete rows and columns dynamically
  • Best practices for inplace vs assignment-based updates

✂️ 1. Slicing Rows by Position

import pandas as pd

df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie', 'David'],
    'Age': [24, 30, 22, 28],
    'Score': [85.0, 92.5, 88.3, 79.5]
})

print(df[1:3])  # Slicing by row position

👉 Output:

     Name  Age  Score
1     Bob   30   92.5
2  Charlie   22   88.3

✅ Basic Python slicing can be used directly on DataFrames for rows.


🔍 2. Slicing Rows and Columns Using .iloc[]

print(df.iloc[0:2, 1:])  # Rows 0–1, Columns 1 onward

👉 Output:

   Age  Score
0   24   85.0
1   30   92.5

.iloc[] is integer-position based and uses exclusive end slicing.


🏷️ 3. Slicing by Labels with .loc[]

print(df.loc[1:3, ['Name', 'Score']])

👉 Output:

      Name  Score
1      Bob   92.5
2  Charlie   88.3
3    David   79.5

.loc[] is label-based and inclusive of the end label.


🧾 4. Accessing Single Values

print(df.loc[2, 'Score'])    # Label-based
print(df.iloc[2, 2])         # Position-based

👉 Output:

88.3
88.3

✅ Combine row and column access for granular control.


🔧 5. Modify a Single Value

df.at[0, 'Age'] = 25     # Fast label-based access
df.iat[3, 2] = 80.0      # Fast position-based access

✅ Use .at[] or .iat[] for faster cell modifications.


🧱 6. Modify an Entire Column

df['Score'] = df['Score'] + 5   # Add bonus points
df['Passed'] = df['Score'] >= 85

👉 Output:

     Name  Age  Score  Passed
0   Alice   25   90.0    True
1     Bob   30   97.5    True
2  Charlie   22   93.3    True
3   David   28   85.0    True

✅ Series operations broadcast across the entire column.


🔁 7. Modify a Row

df.loc[2] = ['Chuck', 23, 91.0, True]

✅ Assign a list to replace all values in a row.


➕ 8. Add New Column

df['Grade'] = ['A', 'A+', 'A', 'B']

✅ Columns can be created on the fly with default or calculated values.


➖ 9. Delete Column or Row

df = df.drop('Grade', axis=1)      # Delete column
df = df.drop(1, axis=0)            # Delete row

✅ Use axis=1 for columns and axis=0 for rows.


🔁 10. Inplace vs Copy Behavior

df.drop('Score', axis=1, inplace=True)   # Modify original

✅ Use inplace=True to avoid reassignment.


📌 Summary – Recap & Next Steps

Slicing and modifying DataFrames is a core part of exploratory data analysis and transformation workflows. With .loc[], .iloc[], .at[], and .iat[], you gain powerful tools to access and reshape your data with precision.

🔍 Key Takeaways:

  • Use .iloc[] for position-based slicing and .loc[] for label-based
  • Modify cells, rows, or columns using direct assignment
  • Use drop() to remove rows/columns and inplace=True for memory efficiency
  • Create new columns dynamically with calculations or conditions

⚙️ Real-world relevance: Used in data wrangling, feature engineering, data cleaning, and all forms of business reporting and scientific analysis.


❓ FAQs – Slicing and Modifying DataFrames

❓ Can I slice both rows and columns at once?
✅ Yes. Use .iloc[row_start:row_end, col_start:col_end] or .loc[row_range, column_list].

❓ How do I change a specific value in a DataFrame?
Use .at[] or .iat[] for fast scalar updates:

df.at[1, 'Age'] = 31

❓ What’s the difference between drop() and del?

  • drop() can remove rows or columns and works with inplace=True
  • del removes columns only:
del df['ColumnName']

❓ How can I add multiple columns at once?
Assign a dictionary to df[['Col1', 'Col2']] or use assignment in a loop.

❓ Are DataFrame modifications permanent?
❌ Not unless you use inplace=True or assign the result back to df.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Pandas Slicing and Modifying DataFrames

Or Copy Link

CONTENTS
Scroll to Top