Insert Column at Specific Position of pandas DataFrame in Python (2 Examples) | Middle or Beginning

Опубликовано: 12 Сентябрь 2024
на канале: Statistics Globe
454
9

How to add a column at a certain location of a pandas DataFrame in the Python programming language. More details:
Python code of this video:

import pandas as pd # Import pandas library

data = pd.DataFrame({'x1':range(10, 16), # Create example DataFrame
'x2':[1, 1, 1, 1, 1, 1],
'x3':[5, 2, 6, 5, 8, 1]})
print(data) # Print example DataFrame

new_col = ['a', 'b', 'c', 'd', 'e', 'f'] # Create example list
print(new_col) # Print example list
# ['a', 'b', 'c', 'd', 'e', 'f']

data_new1 = data.copy() # Create duplicate of data
data_new1.insert(loc = 2, column = 'new', value = new_col) # Insert column
print(data_new1) # Print updated data

data_new2 = data.copy() # Create duplicate of data
data_new2.insert(loc = 0, column = 'new', value = new_col) # Add column
print(data_new2) # Print updated data

Follow me on Social Media:
Facebook – Statistics Globe Page:
Facebook – R Programming Group for Discussions & Questions:
Facebook – Python Programming Group for Discussions & Questions:
LinkedIn – Statistics Globe Page:
LinkedIn – R Programming Group for Discussions & Questions:
LinkedIn – Python Programming Group for Discussions & Questions:
Twitter:

Music by bensound.com