Page 206 - Touhpad Ai
P. 206
Selecting the Specific Element
To access a specific element in a DataFrame, you can use the .iloc[] method to access the element by using its row and
column index.
Program 13: To select a specific element from the DataFrame
# Import pandas library
import pandas as pd
# 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)
# Accessing a specific element
element = df.iloc[1, 2] # Row index 1, Column index 2
print("Element at (1, 2):", element)
Output:
Element at (1, 2): Kanpur
Adding a New Column to the DataFrame
You can add a column in a DataFrame by directly assigning values to a new column using the DataFrame's bracket
notation. This will add the columns at the end of the DataFrame.
Program 14: To add a new column to the end of the DataFrame
# Import pandas library
import pandas as pd
# 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]
# Displaying DataFrame
print(df[['Name', 'Age', 'Address', 'Qualification', 'Salary']])
204 Touchpad Artificial Intelligence - XI

