0
$\begingroup$

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.

$\endgroup$
1
$\begingroup$

No the cleanest solution but it works

currentyear = 2021

df["Vals"] = df.apply(lambda x: x["column1"] if x["y1"] == currentyear else x["column2"] if x["y2"] == currentyear else x["column3"], axis = 1)

Hope it helps

$\endgroup$
0
$\begingroup$

I think this should work

df['vals'] = [x1 if y1 == currentyear else x2 if y2 == currentyear for x1, x2, y1, y2 in zip(df['col1'],df['col2'],df['y1'],df['y2'])]
$\endgroup$
2
  • $\begingroup$ Thanks for the answers, however it doesn't recognize multiple variables in for loop and gives syntax error df['GPEUR'] = [x1 if y1 == currentyear else x2 if y2 == currentyear for x1, x2, y1, y2 in zip(df['y_1grossprofiteur'],df['y2grossprofiteur'],df['y_1'],df['y2'])] ^ SyntaxError: invalid syntax $\endgroup$ Jul 13 at 10:13
  • $\begingroup$ I don't know then... You should directly post this question to Stack Overflow, since that's directly code-related $\endgroup$
    – BeamsAdept
    Jul 13 at 10:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.