To add a new row to a Pandas DataFrame, you can use one of the following methods:
Method 1: Append a Dictionary to the DataFrame
You can append a dictionary to the DataFrame using the append()
method. Here is an example:
pythonimport pandas as pd
# create a DataFrame
df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 35]})
# create a dictionary for the new row
new_row = {'Name': 'Dave', 'Age': 40}
# append the dictionary to the DataFrame
df = df.append(new_row, ignore_index=True)
# print the updated DataFrame
print(df)
In this example, we first create a DataFrame with three rows. We then create a dictionary new_row
for the new row we want to add. We use the append()
method to add the new row to the DataFrame. The ignore_index=True
parameter tells Pandas to reset the index of the DataFrame after appending the new row.
Method 2: Append a Series to the DataFrame
You can also append a Pandas Series to the DataFrame using the loc[]
method. Here is an example:
pythonimport pandas as pd
# create a DataFrame
df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 35]})
# create a Pandas Series for the new row
new_row = pd.Series(['Dave', 40], index=df.columns)
# append the Series to the DataFrame
df = df.append(new_row, ignore_index=True)
# print the updated DataFrame
print(df)
In this example, we first create a DataFrame with three rows. We then create a Pandas Series new_row
for the new row we want to add. We use the loc[]
method to append the new row to the DataFrame. The ignore_index=True
parameter tells Pandas to reset the index of the DataFrame after appending the new row.
Both methods should produce the same output DataFrame:
Name Age 0 John 25 1 Alice 30 2 Bob 35 3 Dave 40
Comments
Post a Comment