You can add a row in Pandas DataFrame with any of the following methods. I highly recommend you This book to learn Python. In this article, you will see 4 methods to add a row in Pandas DataFrame.
- df.append()
- df.loc[ ]
- df.iloc[ ]
- pd.concat()
Step 1: Install Pandas Library
Install the Pandas library using this code, if it is not installed.
pip install pandas
Method 1: Using df.append()
# Import the Pandas library as pd import pandas as pd # Initialize a dictionary dict = {'Names':['Harry', 'John', 'Ali', 'Messi'], 'Marks':[95, 90, 87, 85]} # Convert the dictionary into DataFrame df = pd.DataFrame(dict) # Display the Original DataFrame print(df) # New Row row = {'Names':'Hussain', 'Marks': 92} # Add a row in DataFrame df1 = df.append(row, ignore_index = True) # Display the New DataFrame print(df1)
Output:
Names Marks 0 Harry 95 1 John 90 2 Ali 87 3 Messi 85 Names Marks 0 Harry 95 1 John 90 2 Ali 87 3 Messi 85 4 Hussain 92
Method 2: Using df.loc[ ]
# Import the Pandas library as pd import pandas as pd # Initialize a dictionary dict = {'Names':['Harry', 'John', 'Ali', 'Messi'], 'Marks':[95, 90, 87, 85]} # Convert the dictionary into DataFrame df = pd.DataFrame(dict) # Display the Original DataFrame print(df) # New Row row = {'Names':'Hussain', 'Marks': 92} # Add a row in DataFrame df.loc[len(df)] = row # Display the DataFrame print(df)
Output:
Names Marks 0 Harry 95 1 John 90 2 Ali 87 3 Messi 85 Names Marks 0 Harry 95 1 John 90 2 Ali 87 3 Messi 85 4 Hussain 92
Method 3: Using df.iloc[ ]
# Import the Pandas library as pd import pandas as pd # Initialize a dictionary dict = {'Names':['Harry', 'John', 'Ali', 'Messi'], 'Marks':[95, 90, 87, 85]} # Convert the dictionary into DataFrame df = pd.DataFrame(dict) # Display the Original DataFrame print(df) # New Row row = {'Names':'Hussain', 'Marks': 92} # Add new row in DataFrame at specific index df.iloc[2] = row # Display the New DataFrame print(df)
Output:
Names Marks 0 Harry 95 1 John 90 2 Ali 87 3 Messi 85 Names Marks 0 Harry 95 1 John 90 2 Hussain 92 3 Messi 85
Method 4: Using pd.concat()
# Import the Pandas library as pd import pandas as pd # Initialize a dictionary dict = {'Names':['Harry', 'John', 'Ali', 'Messi'], 'Marks':[95, 90, 87, 85]} # Convert the dictionary into DataFrame df = pd.DataFrame(dict) # Display the Original DataFrame print(df) # New Row row = pd.DataFrame({'Names':'Hussain', 'Marks': 92}, index=[0]) # Add a row in DataFrame df1 = pd.concat([df, row], ignore_index=True, sort=False) # Display the DataFrame print(df1)
Output:
Names Marks 0 Harry 95 1 John 90 2 Ali 87 3 Messi 85 Names Marks 0 Harry 95 1 John 90 2 Ali 87 3 Messi 85 4 Hussain 92