df = pd.DataFrame(data={
"id": ['a', 'a', 'b', 'b', 'a', 'c', 'c', 'b'],
"transaction_amount": [110, 0, 10, 30, 40.4, 62.2, 20, 20],
"principal_amount": [100, 0, 0, 0, 40, 60, 0, 0],
"interest_amount": [10, 0, 10, 0, 0.4, 0.6, 10, 0],
"overpayment_amount": [0, 0, 0, 0, 0, 1.6, 10, 20],
})
I have the above dataframe.
I want to have a column ,amount, and populate it as follows:
- Create a row for each
principal_amount,interest_amountandoverpayment_amountif it's value is not 0, and assignprincipal,interestandoverpaymentto a new column,transaction_type, respectively. - Get value from
transaction_amountif other three column values are 0 for that row.
The output should look like this:
amount transaction_type id
3 30.0 NaN b
0 100.0 principal a
4 40.0 principal a
5 60.0 principal c
0 10.0 interest a
2 10.0 interest b
4 0.4 interest a
5 0.6 interest c
6 10.0 interest c
5 1.6 overpayment c
6 10.0 overpayment c
7 20.0 overpayment b
My current solution:
import pandas as pd
df = pd.DataFrame(data={
"id": ['a', 'a', 'b', 'b', 'a', 'c', 'c', 'b'],
"transaction_amount": [110, 0, 10, 30, 40.4, 62.2, 20, 20],
"principal_amount": [100, 0, 0, 0, 40, 60, 0, 0],
"interest_amount": [10, 0, 10, 0, 0.4, 0.6, 10, 0],
"overpayment_amount": [0, 0, 0, 0, 0, 1.6, 10, 20],
})
columns = ["amount", "transaction_type"]
output_df = pd.DataFrame(columns=columns)
# Add transaction amount
condition = (df["principal_amount"] == 0) & (df["interest_amount"] == 0) & (df["overpayment_amount"] == 0) & (df["transaction_amount"] != 0)
subdf = df.loc[condition, ['id', 'transaction_amount']]
subdf = subdf.rename(columns={'transaction_amount': "amount"})
output_df = output_df.append(subdf)
# Add principal and interest
for field in ["principal_amount", "interest_amount", "overpayment_amount"]:
subdf = df.loc[df[field] != 0, ['id', field]]
subdf["transaction_type"] = field.split("_")[0]
subdf = subdf.rename(columns={field: "amount"})
output_df = output_df.append(subdf)
Is there any pandas feature that helps me do this implementation more concise and efficient?