Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📊 Unit 1 – DataFrame  ·  Lesson 10

DataFrame: loc, iloc, Add & Delete

Selecting columns

df
MathsIPCity
Asha7888Delhi
Ravi9281Pune
Neha6595Delhi
Om8874Agra
df.loc['Ravi':'Neha', 'Maths':'IP'] = df.iloc[1:3, 0:2]
Python
import pandas as pd
df = pd.DataFrame({'Maths': [78, 92, 65, 88], 'IP': [88, 81, 95, 74],
                   'City': ['Delhi', 'Pune', 'Delhi', 'Agra']},
                  index=['Asha', 'Ravi', 'Neha', 'Om'])
print(df['IP'])                     # one column -> Series
print(df[['Maths', 'City']])        # list of columns -> DataFrame
print(df.City.tolist())             # dot notation
Asha 88 Ravi 81 Neha 95 Om 74 Name: IP, dtype: int64 Maths City Asha 78 Delhi Ravi 92 Pune Neha 65 Delhi Om 88 Agra ['Delhi', 'Pune', 'Delhi', 'Agra']

Rows and cells with loc

df.loc[rows, columns] uses labels; slice ends are included.

Python
import pandas as pd
df = pd.DataFrame({'Maths': [78, 92, 65, 88], 'IP': [88, 81, 95, 74],
                   'City': ['Delhi', 'Pune', 'Delhi', 'Agra']},
                  index=['Asha', 'Ravi', 'Neha', 'Om'])
print(df.loc['Ravi'])                         # one row
print(df.loc['Ravi':'Neha', 'Maths':'IP'])    # labels, end included
print(df.loc['Om', 'City'])                   # one cell
Maths 92 IP 81 City Pune Name: Ravi, dtype: object Maths IP Ravi 92 81 Neha 65 95 Agra

Rows and cells with iloc

df.iloc[rows, columns] uses positions 0, 1, 2 …; slice ends are excluded.

Python
import pandas as pd
df = pd.DataFrame({'Maths': [78, 92, 65, 88], 'IP': [88, 81, 95, 74],
                   'City': ['Delhi', 'Pune', 'Delhi', 'Agra']},
                  index=['Asha', 'Ravi', 'Neha', 'Om'])
print(df.iloc[0])                 # first row
print(df.iloc[1:3, 0:2])          # positions, end excluded
print(df.iloc[-1, 2])             # last row, third column
Maths 78 IP 88 City Delhi Name: Asha, dtype: object Maths IP Ravi 92 81 Neha 65 95 Agra

Boolean indexing

Python
import pandas as pd
df = pd.DataFrame({'Maths': [78, 92, 65, 88], 'IP': [88, 81, 95, 74],
                   'City': ['Delhi', 'Pune', 'Delhi', 'Agra']},
                  index=['Asha', 'Ravi', 'Neha', 'Om'])
print(df[df['IP'] > 80])
print(df.loc[df.City == 'Delhi', ['Maths']])
print(df[(df.Maths > 70) & (df.IP > 80)].index.tolist())
Maths IP City Asha 78 88 Delhi Ravi 92 81 Pune Neha 65 95 Delhi Maths Asha 78 Neha 65 ['Asha', 'Ravi']

Adding rows and columns

Python
import pandas as pd
df = pd.DataFrame({'Maths': [78, 92, 65], 'IP': [88, 81, 95]},
                  index=['Asha', 'Ravi', 'Neha'])
df['Total'] = df['Maths'] + df['IP']          # new column from others
df['Remark'] = 'Pass'                         # same value in all rows
df.loc['Om'] = [88, 74, 162, 'Pass']          # new row
df.at['Neha', 'Remark'] = 'Topper'            # change one cell
print(df)
Maths IP Total Remark Asha 78 88 166 Pass Ravi 92 81 173 Pass Neha 65 95 160 Topper Om 88 74 162 Pass

Deleting with drop()

axis = 0

  • Rows
  • df.drop('Ravi')
  • Default

axis = 1

  • Columns
  • df.drop('City', axis=1)
  • Must be written
Python
import pandas as pd
df = pd.DataFrame({'Maths': [78, 92, 65, 88], 'IP': [88, 81, 95, 74],
                   'City': ['Delhi', 'Pune', 'Delhi', 'Agra']},
                  index=['Asha', 'Ravi', 'Neha', 'Om'])
print(df.drop('City', axis=1))                # delete a column
print(df.drop(['Ravi', 'Om']))                # delete rows (axis=0 default)
df.drop('IP', axis=1, inplace=True)           # change df itself
print(df.columns.tolist())
Maths IP Asha 78 88 Ravi 92 81 Neha 65 95 Om 88 74 Maths IP City Asha 78 88 Delhi Neha 65 95 Delhi ['Maths', 'City']

Renaming labels

Python
import pandas as pd
df = pd.DataFrame({'M': [78, 92], 'I': [88, 81]}, index=['r1', 'r2'])
df = df.rename(columns={'M': 'Maths', 'I': 'IP'}, index={'r1': 'Asha', 'r2': 'Ravi'})
print(df)
Maths IP Asha 78 88 Ravi 92 81

Looping: iterrows() and items()

Python
import pandas as pd
df = pd.DataFrame({'Maths': [78, 92, 65], 'IP': [88, 81, 95]},
                  index=['Asha', 'Ravi', 'Neha'])
for name, row in df.iterrows():               # row by row
    print(name, row['Maths'], row['IP'], 'Total =', row.sum())
for col, values in df.items():                # column by column
    print(col, 'average', round(values.mean(), 1))
Asha 78 88 Total = 166 Ravi 92 81 Total = 173 Neha 65 95 Total = 160 Maths average 78.3 IP average 88.0

Frequently Asked Questions

What does axis=1 mean in drop()?
axis=1 works on columns; axis=0 (the default) works on rows.
What is inplace=True?
It changes the original DataFrame instead of returning a new one.
Is iterrows() row-wise or column-wise?
Row-wise: it gives (index, row as Series). items() is column-wise: it gives (column name, column as Series).
← Class 12 Informatics Practices
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicImporting & Exporting CSV Your progress: 10 / 25 (40%) · Lesson 11 / 25 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free