Add New pandas DataFrame Rows in for Loop in Python (Example Code)
In this article you’ll learn how to add new rows to a pandas DataFrame using a for loop in the Python programming language.
Preparing the Example
import pandas as pd # Import pandas library to Python |
import pandas as pd # Import pandas library to Python
my_df = pd.DataFrame({'A':range(18, 23), # Construct pandas DataFrame 'B':['x', 'y', 'y', 'y', 'x'], 'C':range(5, 0, - 1)}) print(my_df) # A B C # 0 18 x 5 # 1 19 y 4 # 2 20 y 3 # 3 21 y 2 # 4 22 x 1 |
my_df = pd.DataFrame({'A':range(18, 23), # Construct pandas DataFrame 'B':['x', 'y', 'y', 'y', 'x'], 'C':range(5, 0, - 1)}) print(my_df) # A B C # 0 18 x 5 # 1 19 y 4 # 2 20 y 3 # 3 21 y 2 # 4 22 x 1
Example: Append Rows to pandas DataFrame within for Loop
my_df_new = my_df.copy() # Create copy of DataFrame for i in range(1, 4): # Add rows at the bottom my_df_new.loc[len(my_df_new)] = i + 10 * 2 print(my_df_new) # Display new DataFrame # A B C # 0 18 x 5 # 1 19 y 4 # 2 20 y 3 # 3 21 y 2 # 4 22 x 1 # 5 21 21 21 # 6 22 22 22 # 7 23 23 23 |
my_df_new = my_df.copy() # Create copy of DataFrame for i in range(1, 4): # Add rows at the bottom my_df_new.loc[len(my_df_new)] = i + 10 * 2 print(my_df_new) # Display new DataFrame # A B C # 0 18 x 5 # 1 19 y 4 # 2 20 y 3 # 3 21 y 2 # 4 22 x 1 # 5 21 21 21 # 6 22 22 22 # 7 23 23 23
Related Tutorials & Further Resources
Have a look at the following Python tutorials. They discuss topics such as dates and extracting data: