Add New Variable at Particular Location of pandas DataFrame in Python (Example Code)
In this post you’ll learn how to add a column at a particular location of a pandas DataFrame in the Python programming language.
Preparing the Example
import pandas as pd # Load pandas library |
import pandas as pd # Load pandas library
my_df = pd.DataFrame({'A':[5, 7, 4, 1, 2, 8, 2], # Construct example DataFrame in Python 'B':[1, 2, 3, 4, 5, 1, 6]}) print(my_df) # Display example DataFrame in console # A B # 0 5 1 # 1 7 2 # 2 4 3 # 3 1 4 # 4 2 5 # 5 8 1 # 6 2 6 |
my_df = pd.DataFrame({'A':[5, 7, 4, 1, 2, 8, 2], # Construct example DataFrame in Python 'B':[1, 2, 3, 4, 5, 1, 6]}) print(my_df) # Display example DataFrame in console # A B # 0 5 1 # 1 7 2 # 2 4 3 # 3 1 4 # 4 2 5 # 5 8 1 # 6 2 6
my_col = [10, 11, 12, 13, 14, 15, 16] # Create new column print(my_col) # Display new column # [10, 11, 12, 13, 14, 15, 16] |
my_col = [10, 11, 12, 13, 14, 15, 16] # Create new column print(my_col) # Display new column # [10, 11, 12, 13, 14, 15, 16]
Example: Inserting New Variable within pandas DataFrame Using insert() Function
my_df.insert(loc = 1, column = 'my_col', value = my_col) # Insert column print(my_df) # Display new data # A my_col B # 0 5 10 1 # 1 7 11 2 # 2 4 12 3 # 3 1 13 4 # 4 2 14 5 # 5 8 15 1 # 6 2 16 6 |
my_df.insert(loc = 1, column = 'my_col', value = my_col) # Insert column print(my_df) # Display new data # A my_col B # 0 5 10 1 # 1 7 11 2 # 2 4 12 3 # 3 1 13 4 # 4 2 14 5 # 5 8 15 1 # 6 2 16 6