Page 208 - Touhpad Ai
P. 208

Program 16: 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 17: To add the row at middle 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.']}





                 206    Touchpad Artificial Intelligence - XI
   203   204   205   206   207   208   209   210   211   212   213