A row can be added to a DataFrame based on different conditions using the following steps:
append()
method to add the new row to the DataFrame.Here is an example:
import pandas as pd
# create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# add a new row if age is less than 30
if df['Age'].max() < 30:
new_row = {'Name': 'David', 'Age': 21}
df = df.append(new_row, ignore_index=True)
# add a new row if name is 'Bob'
if 'Bob' in df['Name'].tolist():
new_row = {'Name': 'Eve', 'Age': 27}
df = df.append(new_row, ignore_index=True)
print(df)
In this example, a new row is added to the DataFrame if the maximum age is less than 30 or if the name 'Bob' is already in the DataFrame. The append()
method is used to add the new row, and the ignore_index=True
parameter is used to reset the index of the DataFrame.
Asked: 2021-11-17 11:00:00 +0000
Seen: 8 times
Last updated: Dec 21 '21