rujole13
rujole13

Reputation: 59

Append row in dataframe if certain condition is met in another row of the dataframe

I have a dataframe that looks like this:

BILL_NO   CREATED_DATE   ACCT_NO   LOCATION   AMOUNT
100       4/6/2021       7551      1150       1000.00
200       4/6/2021       7551      1101       500.00
300       4/6/2021       7551      2025       700.00

What I want to do is this:

If the value '1550' is in column 'LOCATION' in the dataframe, append a row with the same values except the location will be '2051' and the amount should be divided between the two.

Out put should look like this:

BILL_NO   CREATED_DATE   ACCT_NO   LOCATION   AMOUNT
100       4/6/2021       7551      1150       500.00
200       4/6/2021       7551      1101       500.00
300       4/6/2021       7551      2025       700.00
100       4/6/2021       7551      2051       500.00

I've tried writing a function and using a lambda expression for this but all the amounts get turned into NaN values and no row gets appended.

Upvotes: 0

Views: 1375

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150745

Try your logic here:

# all the location 1150
mask = df.LOCATION==1150

# divide by two
df.loc[mask, 'AMOUNT']/=2

# append those rows with new location value
df.append(df.loc[mask].assign(LOCATION=2051))

Output:

   BILL_NO CREATED_DATE  ACCT_NO  LOCATION  AMOUNT
0      100     4/6/2021     7551      1150   500.0
1      200     4/6/2021     7551      1101   500.0
2      300     4/6/2021     7551      2025   700.0
3      100     4/6/2021     7551      2051   500.0

Upvotes: 2

Related Questions