Create a new df column with the maximum of the other columns involving shift()

Viewed 33

I have a DF as follows:

d1=pd.DataFrame({'a':[0,1,0,1,2,4,5,1,7,8,0],'b':[0,1,2,4,5,7,1,3,1,0,1]})

enter image description here

I want to produce a new column called 'new' that is based on the maximum of column a and the previous row's value of column b (i.e. 'b' shift()).

I tried doing the follow:

df'[new']=df[['a',df['b'].shift()]].max(axis=1)

Yet I get some mutable error message.

My desired output is as follows:

enter image description here

1 Answers

IIUC, you can try:

df['new_col'] = df.assign(b = df['b'].shift(fill_value = 0)).max(axis =1)

OUTPUT:

    a  b  new_col
0   0  0        0
1   1  1        1
2   0  2        1
3   1  4        2
4   2  5        4
5   4  7        5
6   5  1        7
7   1  3        1
8   7  1        7
9   8  0        8
10  0  1        0

NOTE: If you wanna be more specific about the columns.

df['new_col'] = df.assign(b=df['b'].shift(fill_value=0))[
    ['a', 'b']].max(axis=1)
df['new_col'] = pd.concat([df['b'].shift(fill_value=0), df['a']], 1).max(1)
Related