Ask Your Question
3

How can a row be added to a python dataframe based on different conditions?

asked 2021-11-17 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-12-21 05:00:00 +0000

lalupa gravatar image

A row can be added to a DataFrame based on different conditions using the following steps:

  1. Identify the conditions that need to be met for the new row to be added.
  2. Create a dictionary with the data for the new row. The keys in the dictionary should match the column names in the DataFrame.
  3. Use the 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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-17 11:00:00 +0000

Seen: 8 times

Last updated: Dec 21 '21