How to add one row in an existing Pandas DataFrame?
Published on Aug. 22, 2023, 12:15 p.m.
To add one row to an existing Pandas DataFrame, you can use the loc
method or the append
method. Here’s an example using the loc
method:
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
# create a new row to add to the dataframe
new_row = {'A': 5, 'B': 6}
# add the new row to the dataframe using the loc method
df.loc[len(df)] = new_row
# print the updated dataframe
print(df)
In this example, we first create a sample dataframe using the pd.DataFrame()
method. We then create a dictionary representing the new row we want to add to the dataframe. Finally, we use the loc
method to add the new row to the end of the dataframe, with the index value set to len(df)
to ensure the new row is appended at the end.
Alternatively, you can use the append
method to add the new row as a new dataframe and concatenate it with the original dataframe:
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
# create a new row to add to the dataframe
new_row = {'A': 5, 'B': 6}
# append the new row to the dataframe using the append method
df = df.append(new_row, ignore_index=True)
# print the updated dataframe
print(df)
In this example, we first create a sample dataframe, a dictionary representing the new row, then we use the append()
method as a new DataFrame with the ignore_index=True
argument to ensure the new row is appended to the end of the dataframe with a new index.