Tuesday 10 October 2023

How to Insert a New Column at a Specific Location in a Pandas DataFrame?

Using DataFrame insert method, we can insert a new column at the specific location.

Example

df.insert(loc=1, column='Country', value='India')

 

Above statement add new column ‘Country’ with a static value ‘India’ at the location 1.

 

insert_new_column_at_specific_location.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel', 'Gopi', 'Jitendra', "Raj"],
        'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai']}

df = pd.DataFrame(data)
print(df)

# Add new column Country with value 'India'
print('\nInsert new column Country with value "India" at the location 1')
df.insert(loc=1, column='Country', value='India')
print(df)

 

Output

       Name  Age       City
0   Krishna   34  Bangalore
1       Ram   25    Chennai
2      Joel   29  Hyderabad
3      Gopi   41  Hyderabad
4  Jitendra   52  Bangalore
5       Raj   23    Chennai

Insert new column Country with value "India" at the location 1
       Name Country  Age       City
0   Krishna   India   34  Bangalore
1       Ram   India   25    Chennai
2      Joel   India   29  Hyderabad
3      Gopi   India   41  Hyderabad
4  Jitendra   India   52  Bangalore
5       Raj   India   23    Chennai

  As you see above output, Country column is added at the location 1, after Name column.

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment