add a line in a dataframe in python

To add a line to a pandas DataFrame in Python, you can use the append() method. Here's an example:

main.py
import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35]})

# create a new row to add
new_row = {'name': 'Dave', 'age': 40}

# append the new row to the DataFrame
df = df.append(new_row, ignore_index=True)

# print the updated DataFrame
print(df)
315 chars
14 lines

Output:

main.py
       name  age
0     Alice   25
1       Bob   30
2   Charlie   35
3      Dave   40
85 chars
6 lines

In this example, we create a sample DataFrame with three rows. We then create a new row to add to the DataFrame using a Python dictionary. Finally, we use the append() method to add the new row to the DataFrame, and the ignore_index=True parameter ensures that a new index is created for the updated DataFrame.

gistlibby LogSnag