Page 218 - AI Ver 3.0 Class 11
P. 218
# Define a dictionary containing employee data
data = {'Name':['Adit', 'Ekam', 'Sakshi', 'Anu'],
'Age':[27, 24, 25, 30],
'Address':['Delhi', 'Kanpur', 'Meerut', 'Indore'],
'Qualification':['M.Sc.', 'MA', 'MCA', 'Ph.D.']}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# Add a new column 'Salary' to the DataFrame
df['Salary'] = [50000, 45000, 55000, 60000]
# Add a new row to the DataFrame using DataFrame.loc[]
new_row = {'Name': 'Himanshi', 'Age': 29, 'Address': 'Mumbai', 'Qualification':
'B.Tech', 'Salary': 52000}
# Index where you want to insert the row
index_to_insert = len(df)//2
# Shift existing rows down and insert new row at index_to_insert
df = pd.concat([df.iloc[:index_to_insert], pd.DataFrame([new_row]), df.iloc[index_
to_insert:]]).reset_index(drop=True)
# Display the DataFrame with the new row in the middle
print("DataFrame with the new row in the middle:")
print(df)
Output:
DataFrame with the new row in the middle:
Name Age Address Qualification Salary
0 Adit 27 Delhi M.Sc. 50000
1 Ekam 24 Kanpur MA 45000
2 Himanshi 29 Mumbai B.Tech 52000
3 Sakshi 25 Meerut MCA 55000
4 Anu 30 Indore Ph.D. 60000
Deleting Rows & Columns from a DataFrame
Deleting rows and columns from a DataFrame can be accomplished using the drop() method. This method allows you to
specify which rows or columns to delete and whether to make the changes in place or return a new DataFrame.
To remove rows and columns from a DataFrame, we specify the labels' names and the axis (0 for rows, 1 for columns).
Program 53: To delete rows and columns from the DataFrame
# Import pandas library
import pandas as pd
216 Touchpad Artificial Intelligence (Ver. 3.0)-XI

