append a line at the end of a dataframe in python

To append a new row to a Pandas DataFrame in Python, you can use the append() function with the loc[] or iloc[] methods to specify the location of the new row.

Here is a sample code snippet that demonstrates how to append a new row to a DataFrame using the loc[] method:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})

# create a new row to append to the dataframe
new_row = {'Name': 'Charlie', 'Age': 35}

# append the new row to the dataframe
df.loc[len(df)] = new_row

# print the updated dataframe
print(df)
306 chars
14 lines

Output:

main.py
      Name  Age
0    Alice   25
1      Bob   30
2  Charlie   35
64 chars
5 lines

In this example, we first create a simple DataFrame with two rows using the pd.DataFrame() function. Next, we define a new row as a Python dictionary with the same column names as the DataFrame. Finally, we use the loc[] method with the len() function to append the new row to the end of the DataFrame.

gistlibby LogSnag