Split Columns with Condition in Pandas Data frame
Question:
I have a "Code" and "Amount column. I need to split both of them into three different columns based on the condition. Example:
Code
Amount
1
$40.00
1
$20.00
Condition: First $5.00 goes to Code1, $10.00 goes to Code2 and
Output:
Code
Amount
Code1
Amount1
Code2
Amount2
Code3
Amount3
1
$40.00
1.1
$5.00
1.2
$10.00
1.3
$25.00
1
$20.00
1.1
$5.00
1.2
$10.00
1.3
$5.00
I tried apply function but I am not getting any desired results.
Answers:
You can use a loop:
subamounts = [5, 10, 1000]
l = [df]
remainder = df['Amount']
for i, x in enumerate(subamounts, start=1):
remainder = remainder.sub(x)
l.append(pd.DataFrame({f'Code{i}': df['Code'].astype(str).add(f'.{i}'),
f'Amount {i}': x+remainder.clip(upper=0)
}))
remainder = remainder.clip(lower=0)
out = pd.concat(l, axis=1)
Output (with more examples):
Code Amount Code1 Amount 1 Code2 Amount 2 Code3 Amount 3
0 1 40.0 1.1 5.0 1.2 10.0 1.3 25.0
1 1 20.0 1.1 5.0 1.2 10.0 1.3 5.0
2 1 7.0 1.1 5.0 1.2 2.0 1.3 0.0
3 1 3.0 1.1 3.0 1.2 0.0 1.3 0.0
I have a "Code" and "Amount column. I need to split both of them into three different columns based on the condition. Example:
Code | Amount |
---|---|
1 | $40.00 |
1 | $20.00 |
Condition: First $5.00 goes to Code1, $10.00 goes to Code2 and
Output:
Code | Amount | Code1 | Amount1 | Code2 | Amount2 | Code3 | Amount3 |
---|---|---|---|---|---|---|---|
1 | $40.00 | 1.1 | $5.00 | 1.2 | $10.00 | 1.3 | $25.00 |
1 | $20.00 | 1.1 | $5.00 | 1.2 | $10.00 | 1.3 | $5.00 |
I tried apply function but I am not getting any desired results.
You can use a loop:
subamounts = [5, 10, 1000]
l = [df]
remainder = df['Amount']
for i, x in enumerate(subamounts, start=1):
remainder = remainder.sub(x)
l.append(pd.DataFrame({f'Code{i}': df['Code'].astype(str).add(f'.{i}'),
f'Amount {i}': x+remainder.clip(upper=0)
}))
remainder = remainder.clip(lower=0)
out = pd.concat(l, axis=1)
Output (with more examples):
Code Amount Code1 Amount 1 Code2 Amount 2 Code3 Amount 3
0 1 40.0 1.1 5.0 1.2 10.0 1.3 25.0
1 1 20.0 1.1 5.0 1.2 10.0 1.3 5.0
2 1 7.0 1.1 5.0 1.2 2.0 1.3 0.0
3 1 3.0 1.1 3.0 1.2 0.0 1.3 0.0