raja4
raja4

Reputation: 31

Min using right indexing python

I am new to Python. I am stuck on this simple task for quite a while, but can't seem to find an answer.

enter image description here

I have a pandas dataframe, all I am trying to do is take take a min of two columns but where one column is lagged

enter code x = {'A': pd.Series([1,3,6,5,3,2]),
'B': pd.Series([4,2,8,4,4,2])}                                               
 x1 = pd.DataFrame(x)
x1.rolling(2).apply(lambda x: np.min(x['A'].iloc[1],x['B'].iloc[0],axis=1))

This gives me error:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices 

If the code works, the answer should be

c = [NaN,3,2,5,3,2]

Upvotes: 3

Views: 61

Answers (2)

BENY
BENY

Reputation: 323326

Is this what you need ?

np.minimum(x1.A.values,x1.B.shift().values)
Out[603]: array([nan,  3.,  2.,  5.,  3.,  2.])

Upvotes: 1

MissBleu
MissBleu

Reputation: 175

you need to shift the values of the dataframe before calling min

df = pd.DataFrame({'A': [1,3,6,5,3,2],
'B': [4,2,8,4,4,2]}) 
df.B= df.B.shift(+1)
df.min(axis=1, skipna=False)

that should do the trick

Upvotes: 1

Related Questions