Create a Pandas Dataframe by appending one row at a time
Here is an example of creating a Pandas DataFrame by appending one row at a time:
Here is an example of creating a Pandas DataFrame by appending one row at a time:
Creating a Pandas DataFrame by appending one row at a time
import pandas as pd
# Create an empty DataFrame
df = pd.DataFrame(columns=['Name', 'Age'])
# Append rows to the DataFrame (pd.concat is recommended for Pandas 2.0+)
df = pd.concat([df, pd.DataFrame([{'Name': 'John', 'Age': 30}])], ignore_index=True)
df = pd.concat([df, pd.DataFrame([{'Name': 'Mike', 'Age': 25}])], ignore_index=True)
df = pd.concat([df, pd.DataFrame([{'Name': 'Sarah', 'Age': 35}])], ignore_index=True)
# Print the DataFrame
print(df)This will output:
Name Age
0 John 30
1 Mike 25
2 Sarah 35Alternatively, you can use the loc accessor of DataFrame to add the row one by one,
Creating a Pandas DataFrame by appending one row at a time using the loc accessor
df = pd.DataFrame(columns=['Name', 'Age'])
df.loc[0] = ['John', 30]
df.loc[1] = ['Mike', 25]
df.loc[2] = ['Sarah', 35]When using pd.concat, the ignore_index=True parameter resets the DataFrame index to a simple sequence starting from 0. Note that ignore_index is not applicable to the loc accessor.
Note: Appending rows one by one is highly inefficient for large datasets. For better performance, collect your data in a list or dictionary and create the DataFrame in a single step. Also,
df.append()was deprecated in Pandas 1.4 and removed in 2.0;pd.concat()is the modern replacement.