Insert New Row at Arbitrary Position of pandas DataFrame in Python (Example Code)
This tutorial demonstrates how to add a new row at a specific position of a pandas DataFrame in the Python programming language.
Creation of Example Data
import pandas as pd # Import pandas |
import pandas as pd # Import pandas
my_df = pd.DataFrame({"A":["yes", "maybe", "yes", "no", "yes"], # Construct pandas DataFrame "B":range(1, 6), "C":["hey", "hoho", "hi", "huhu", "hello"]}) print(my_df) # A B C # 0 yes 1 hey # 1 maybe 2 hoho # 2 yes 3 hi # 3 no 4 huhu # 4 yes 5 hello |
my_df = pd.DataFrame({"A":["yes", "maybe", "yes", "no", "yes"], # Construct pandas DataFrame "B":range(1, 6), "C":["hey", "hoho", "hi", "huhu", "hello"]}) print(my_df) # A B C # 0 yes 1 hey # 1 maybe 2 hoho # 2 yes 3 hi # 3 no 4 huhu # 4 yes 5 hello
my_list = ["xxx", "yyy", "zzz"] # Construct list object print(my_list) # ['xxx', 'yyy', 'zzz'] |
my_list = ["xxx", "yyy", "zzz"] # Construct list object print(my_list) # ['xxx', 'yyy', 'zzz']
Example: Inserting New Row at an Arbitrary Location of a pandas DataFrame
my_df2 = my_df.copy() # Add new row at certain position my_df2.loc[1.5] = my_list my_df2 = my_df2.sort_index() print(my_df2) # A B C # 0.0 yes 1 hey # 1.0 maybe 2 hoho # 1.5 xxx yyy zzz # 2.0 yes 3 hi # 3.0 no 4 huhu # 4.0 yes 5 hello |
my_df2 = my_df.copy() # Add new row at certain position my_df2.loc[1.5] = my_list my_df2 = my_df2.sort_index() print(my_df2) # A B C # 0.0 yes 1 hey # 1.0 maybe 2 hoho # 1.5 xxx yyy zzz # 2.0 yes 3 hi # 3.0 no 4 huhu # 4.0 yes 5 hello
Related Tutorials & Further Resources
Furthermore, you could have a look at the related articles that I have published on www.data-hacks.com: