Append New Variable to pandas DataFrame in Python (Example Code)
This tutorial shows how to append an additional variable to a pandas DataFrame in Python.
Preparing the Example
import pandas as pd # Load pandas library |
import pandas as pd # Load pandas library
my_df = pd.DataFrame({"col1":range(10, 15), # Constructing pandas DataFrame in Python "col2":["e", "f", "g", "h", "i"], "col3":[5, 1, 7, 2, 1], "col4":range(25, 30)}) print(my_df) # Displaying pandas DataFrame # col1 col2 col3 col4 # 0 10 e 5 25 # 1 11 f 1 26 # 2 12 g 7 27 # 3 13 h 2 28 # 4 14 i 1 29 |
my_df = pd.DataFrame({"col1":range(10, 15), # Constructing pandas DataFrame in Python "col2":["e", "f", "g", "h", "i"], "col3":[5, 1, 7, 2, 1], "col4":range(25, 30)}) print(my_df) # Displaying pandas DataFrame # col1 col2 col3 col4 # 0 10 e 5 25 # 1 11 f 1 26 # 2 12 g 7 27 # 3 13 h 2 28 # 4 14 i 1 29
col5 = ["a", "b", "c", "d", "e"] # Constructing list print(col5) # Displaying list # ['a', 'b', 'c', 'd', 'e'] |
col5 = ["a", "b", "c", "d", "e"] # Constructing list print(col5) # Displaying list # ['a', 'b', 'c', 'd', 'e']
Example: Applying assign Function to Concatenate Additional Column to pandas DataFrame
my_df = my_df.assign(col5 = col5) # Adding new column print(my_df) # Displaying updated DataFrame # col1 col2 col3 col4 col5 # 0 10 e 5 25 a # 1 11 f 1 26 b # 2 12 g 7 27 c # 3 13 h 2 28 d # 4 14 i 1 29 e |
my_df = my_df.assign(col5 = col5) # Adding new column print(my_df) # Displaying updated DataFrame # col1 col2 col3 col4 col5 # 0 10 e 5 25 a # 1 11 f 1 26 b # 2 12 g 7 27 c # 3 13 h 2 28 d # 4 14 i 1 29 e