Issue
my table looks something like this:
Sector | 4/1/2022 | 5/1/2022 | 6/1/2022 | 1Y Min |
---|---|---|---|---|
A | 10 | 05 | 12 | 05 |
B | 18 | 20 | 09 | 09 |
C | 02 | 09 | 12 | 02 |
I want to add a new column "1m change" such that values of the new column is calculated using the formula: (Value as of the latest date - Value as of one month prior to the latest date)
I want to add a new column "YTD change" such that values of the new column is calculated using the formula: (Value as of the latest date - Value as of first date of the year)
I want to keep both the formulas dynamic such that it gets updated whenever a column with a new date is available.
For eg:-
Sector | 1/1/2022 | 5/1/2022 | 6/1/2022 | 1Y Min | 1M Change | YTD Chg |
---|---|---|---|---|---|---|
A | 10 | 05 | 12 | 05 | 7 | 2 |
B | 20 | 20 | 60 | 09 | 40 | 40 |
C | 02 | 09 | 12 | 02 | 3 | 10 |
Solution
Try doing this:
import numpy as np
import pandas as pd
df['1M Change'] = np.nan
df['YTD Chg'] = np.nan
df['1M Change'] = df.iloc[:, -4] - df.iloc[:, -5]
df['YTD Chg'] = df.iloc[:, -4] - df.iloc[:, 1]
def aaa():
df['1M Change'] = df.iloc[:, -4] - df.iloc[:, -5]
df['YTD Chg'] = df.iloc[:, -4] - df.iloc[:, 1]
df.insert(1, "lost", [2, 1, 3], True)
aaa()
print(df)
Immediately added columns: 1M Change, YTD Chg and filled them with empty values. Implicit iloc indexing is used (row index numbers on the left, column index numbers on the right). At the end, I added a column and called in the function to update the columns 1M Change, YTD Chg.
Answered By - inquirer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.