I am trying to create a new column in pandas data frame based on existing columns.
| column1 | column2 | column3 | y1 | y2 | y3 |
|---|---|---|---|---|---|
| 100 | 200 | 300 | 2020 | 2021 | 2022 |
| 100 | 200 | 300 | 2021 | 2022 | 2023 |
| 100 | 200 | 300 | 2019 | 2020 | 2021 |
I want a new columns vals which take values of col1 if currentyear = y1 and col2 if currentyear = y2
| column1 | column2 | column3 | y1 | y2 | y3 | Vals |
|---|---|---|---|---|---|---|
| 100 | 200 | 300 | 2020 | 2021 | 2022 | 200 |
| 100 | 200 | 300 | 2021 | 2022 | 2023 | 100 |
| 100 | 200 | 300 | 2019 | 2020 | 2021 | 300 |
I am trying below code :
def assignvalues(df):
if df['y1'] == currentyear:
df['Vals'] = df['col1']
elif df['y2'] == currentyear:
df['Vals'] = df['col2']
elif df['y3'] == currentyear:
df['Vals'] = df['col3']
df.apply(assignvalues)
It does create columns but doesn't store any values.