I have a dataframe similar to this
data={'COMB':["PNR1", "PNR1", "PNR11", "PNR2", "PNR2"],
'FROM':["MAA", "BLR", "DEL", "TRV", "HYD"],
'TO':["BLR", "MAA", "MAA", "HYD", "TRV"]}
md=pd.DataFrame(data)
md
What I want to do is to create another column based on the condition that if the From of one row is equal to the To of the next row, then it sholud return "R" otherwise it will return "O" in the new column.
My final output should look like this.

Can anyone help me in python. I tried following method, but it gives me error
md_merged=(md>>
group_by('COMB')>>
mutate(TYPE=np.where(md['FROM'].isin(md['TO']),"R","O"))>>
ungroup)
ValueError: Length of values does not match length of index Please help.
This solution compare all values between groups, not only prvious and next.
You can use custom lambda function in
GroupBy.applyfor boolean mask, for avoidMultiIndexis addedgroup_keys=FalsetoDataFrame.groupby, last set new values innumpy.where:This solution compare previous and next rows per groups:
Another idea is use
DataFrameGroupBy.shift, it should be faster likegroupby.apply: