2

I would like to create a new column in Python and place in a specific position. For instance, let "example" be the following dataframe:

import pandas as pd    

example = pd.DataFrame({
            'name': ['alice','bob','charlie'],
            'age': [25,26,27],
            'job': ['manager','clerk','policeman'],
            'gender': ['female','male','male'],
            'nationality': ['french','german','american']
        })

I would like to create a new column to contain the values of the column "age":

example['age_times_two']= example['age'] *2

Yet, this code creates a column at the end of the dataframe. I would like to place it as the third column, or, in other words, the column right next to the column "age". How could this be done:

a) By setting an absolute place to the new column (e.g. third position)?

b) By setting a relative place for the new column (e.g. right to the column "age")?

Incognito
  • 331
  • 1
  • 5
  • 14

3 Answers3

10

You can use df.insert here.

example.insert(2,'age_times_two',example['age']*2)
example
      name  age  age_times_two        job  gender nationality
0    alice   25             50    manager  female      french
1      bob   26             52      clerk    male      german
2  charlie   27             54  policeman    male    american
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
2

This is a bit manual way of doing it:

example['age_times_two']= example['age'] *2

cols = list(example.columns.values)
cols

You get a list of all the columns, and you can rearrange them manually and place them in the code below

example = example[['name', 'age', 'age_times_two', 'job', 'gender', 'nationality']]
torkestativ
  • 352
  • 2
  • 15
1

Another way to do it:

example['age_times_two']= example['age'] *2

cols = example.columns.tolist()

cols = cols[:2]+cols[-1:]+cols[2:-1]

example = example[cols]

print(example)

.

      name  age  age_times_two        job  gender nationality
0    alice   25             50    manager  female      french
1      bob   26             52      clerk    male      german
2  charlie   27             54  policeman    male    american
Anshul
  • 1,413
  • 2
  • 6
  • 14