How to Create A Dataframe and Add Row in Python
To create a dataframe and add a row to it in Python, you can use the pandas.DataFrame() function to create the dataframe and the loc[] method to add a row to it.
The following example shows how to create a dataframe in Python and add a row to it.
Using DataFrame() & loc[] Function
We can use the DataFrame() function from the pandas library and the loc[] method to add a row to it.
Suppose we have the following data:
# Import pandas library
import pandas as pd
# Declare data
data = {
'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
'Price': [4500, 550, 250, 50, 350, 50],
'Status': [1, 1, 1, 0, 1, 1]
}
# Create dataframe
df = pd.DataFrame(data)
# Show dataframe
print(df)
Output: 👇️
Date Product_Code Product_Name Price Status
0 01-03-2023 A-101 Laptop 4500 1
1 01-03-2023 A-102 Mobile 550 1
2 01-03-2023 A-103 Printer 250 1
3 01-03-2023 B-101 Keyboard 50 0
4 02-03-2023 B-102 Scanner 350 1
5 02-03-2023 B-104 Mouse 50 1
The output shows the dataframe created using the DataFrame() function. Now, let’s add a row to the dataframe.
# Add row to dataframe
df.loc[6] = ['03-03-2023', 'A-104', 'Headphones', 100, 1]
# Show updated dataframe
print(df)
Output: 👇️
Date Product_Code Product_Name Price Status
0 01-03-2023 A-101 Laptop 4500 1
1 01-03-2023 A-102 Mobile 550 1
2 01-03-2023 A-103 Printer 250 1
3 01-03-2023 B-101 Keyboard 50 0
4 02-03-2023 B-102 Scanner 350 1
5 02-03-2023 B-104 Mouse 50 1
6 03-03-2023 A-104 Headphones 100 1
In this example, we use the loc[] method to add a new row to the dataframe df.
The output shows the updated dataframe with the new row added.
Conclusion
We can use the DataFrame() function from the pandas library and the loc[] method to create a dataframe and add a row to it in Python.