Page 219 - Ai_V3.0_c11_flipbook
P. 219
# 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]
# Deleting a Row
df.drop(index=1, inplace=True) # Deleting the row with index 1 (Ekam)
print("\nDataFrame after deleting a row:")
print(df)
# Deleting a Column
df.drop(columns='Address', inplace=True) # Deleting the 'Address' column
print("DataFrame after deleting a column:")
print(df)
Output:
DataFrame after deleting a row:
Name Age Address Qualification Salary
0 Adit 27 Delhi M.Sc. 50000
2 Sakshi 25 Meerut MCA 55000
3 Anu 30 Indore Ph.D. 60000
DataFrame after deleting a column:
Name Age Qualification Salary
0 Adit 27 M.Sc. 50000
2 Sakshi 25 MCA 55000
3 Anu 30 Ph.D. 60000
To delete multiple columns with specific labels, you can modify the drop method to include a list of column labels.
DataFrame.drop() method can also be used to remove the duplicate rows.
# Deleting Columns with specific labels
labels_to_delete = ['Age', 'Address'] #specify in a list
df.drop(columns=labels_to_delete, inplace=True)
Python Programming 217

