Page 217 - AI Ver 3.0 Class 11
P. 217

Adding a New Row to the DataFrame
                 A new row can be added to a DataFrame by utilising the DataFrame.loc[] method. This method allows you to add rows
                 by specifying the index and the values.

                  Program 51: To add the row at the end in 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]

                     # Add a new row to the DataFrame using DataFrame.loc[]
                       new_row = {'Name': 'Himanshi', 'Age': 29, 'Address': 'Mumbai', 'Qualification':
                     'B.Tech', 'Salary': 52000}
                     df.loc[len(df)] = new_row


                     # Display the DataFrame with the new row
                     print("DataFrame with the new row:")
                     print(df)
                 Output:
                    DataFrame with the new row:

                           Name   Age   Address  Qualification          Salary
                    0      Adit    27     Delhi               M.Sc.    50000
                    1      Ekam    24    Kanpur                   MA    45000
                    2    Sakshi    25    Meerut                 MCA    55000

                    3       Anu    30    Indore               Ph.D.    60000
                    4  Himanshi    29    Mumbai              B.Tech    52000
                 To add a new row in the middle of the DataFrame, you can use the DataFrame.iloc[] method to specify the index where
                 you want to insert the row.

                  Program 52: To add the row at middle in the DataFrame

                     # Import pandas library
                     import pandas as pd





                                                                                         Python Programming     215
   212   213   214   215   216   217   218   219   220   221   222