Get value from next row in pandas dataframe

دسته‌ها

Next OrderID, next Vendor ID, Next Order Date or any other values from next row, In excel we use this. But what about python, pandas??

we will use the shift() function!!

# getting next vendorID of each User
Orders.sort_values(['UserID','OrderID']  , ascending=False)
Orders.set_index(keys='UserID', inplace=True)
Orders['NextVendorID'] = Orders.groupby('UserID')['VendorID'].shift(-1)
Orders.reset_index(inplace=True)
Orders

Ok, It is done!!

but lets have some other codes too!!

#All Ordersof each customer
Orders.sort_values(['UserID','OrderID']  , ascending=False)
Orders.set_index(keys='UserID', inplace=True)
Orders['AllOrders'] = Orders.groupby('UserID')['OrderID'].nunique()
Orders.reset_index(inplace=True)
Orders
#Next Order Month
 (Mind the difference between years and months! 
#In our database YearMonth is an integer

Orders.sort_values(['UserID','ShamsiYearMonth'] , inplace=True , ascending=False)
Orders['nextOrder'] = Orders.groupby('UserID')['ShamsiYearMonth'].diff()*-1
Orders.loc[(Orders.nextOrder == -0.00),'nextOrder'] = 0
Orders['nextOrder'].value_counts()
# new users of Other Vendors
NewUsers = Orders[Orders['VendorID'] !=1].pivot_table(index='FirstOrderMonth',values='UserID',aggfunc=lambda x: len(x.unique()))
NewUsers.index.rename('ShamsiYearMonth',inplace=True)
NewUsers.rename(columns={'UserID':'NewUsersNDK'},inplace = True)
NewUsers