NTAlgo
NTAlgo

Reputation: 33

Max value between two rows in the same column

I want to add a new column 'B1' which will be the max between the current value of 'b' and the previous value. I have added the max function but it's not working:

data = {
    'a' : [85, 75, 85, 33, 99, 45],
    'b' : [35, 45, 83, 88, 56, 20],
     'c' : [51, 61, 45, 67, 39, 30],
     'd' : [67, 88, 5, 34, 57, 69]
}

df = pd.DataFrame(data)
df['A1'] = df['a'].shift(+1)
df['B1'] = max(df['b'], df['b'].shift(+1))
df.head(10)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Thank you for your help

Upvotes: 0

Views: 579

Answers (2)

Hamza usman ghani
Hamza usman ghani

Reputation: 2243

Use dataframe.max(axis =1):

data = {
    'a' : [85, 75, 85, 33, 99, 45],
    'b' : [35, 45, 83, 88, 56, 20],
     'c' : [51, 61, 45, 67, 39, 30],
     'd' : [67, 88, 5, 34, 57, 69]
}

df = pd.DataFrame(data)
df['A1'] = df['a'].shift(+1)
# df['B1'] = max(df['b'], df['b'].shift(+1))
df['b_shifted']=df["b"].shift()
df["B1"] = df[["b","b_shifted"]].max(axis=1)
df.drop(columns = ["b_shifted"], inplace = True)

Upvotes: 1

Teunis
Teunis

Reputation: 21

Find the max of two or more columns with pandas

You can use .max(axis=1) if you make a new column first. What you are doing now is asking which series is maximum between the two series, which is why you get an ambiguity warning.

Upvotes: 0

Related Questions