Page 216 - AI_Ver_3.0_class_11
P. 216

# Add a new column 'Salary' to the DataFrame
                   df['Salary'] = [50000, 45000, 55000, 60000]


                   # Displaying DataFrame
                        print(df[['Name', 'Age', 'Address', 'Qualification', 'Salary']])
              Output:
                       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

              If you want to add the column at specific position in the DataFrame, then you need to use the insert() function that
              allows you to specify the index value where you want to insert the column.

                Program 50: To add the column at specific position 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)

                   # Specifying values to new column
                   Salary = [50000, 45000, 55000, 60000]


                   # Index position where you want to insert the new column (zero-based)
                   index_position = 2  # Inserting the new column after the 'Age' column

                   # Insert new column at specified index position
                   df.insert(index_position, 'Salary', Salary)

                   # Displaying DataFrame
                   print(df)
              Output:

                       Name     Age   Salary  Address  Qualification
                  0    Adit      27    50000      Delhi             M.Sc.
                  1    Ekam      24    45000  Kanpur                    MA

                  2  Sakshi      25    55000  Meerut                   MCA
                  3     Anu      30     60000  Indore               Ph.D.

                    214     Touchpad Artificial Intelligence (Ver. 3.0)-XI
   211   212   213   214   215   216   217   218   219   220   221