Home > Software engineering >  Add new rows for rows that meet a specific condition in a dataframe
Add new rows for rows that meet a specific condition in a dataframe

Time:04-06

Be the following dataframe in Python:

ID direction
ABC IN
TCV OUT
XYV IN
TCV IN
XYV OUT
AAA IN

I want to define a method that receives an ID and a direction value as parameters and modifies them according to fixed values specified internally in the function. For example:

# Returns the resulting dataframe
df = change_dataframe(df, 'TCV', 'AAA', 'IN')
# Modify only rows with ID equal to 'TCV' and direction attribute value equal to 'IN'. 
# Change the ID from TCV to AAA (specified by parameter) and the direction value 
# from 'IN' to 'OUT' (binary option).

The resulting dataframe is as follows:

ID direction
ABC IN
TCV OUT
XYV IN
AAA OUT
XYV OUT
AAA IN

I hope you can help me to solve the problem.

CodePudding user response:

I assume you mean a Pandas dataframe. This should solve your problem:

def change_dataframe(df, search_id, new_id, direction):
    condition = (df['ID'] == search_id) & (df['direction'] == direction)
    new_direction = "OUT" if direction == "IN" else "IN"
    df['ID'] = df['ID'].mask(condition, new_id)
    df['direction'] = df['direction'].mask(condition, new_direction)
    return df
  • Related