简体   繁体   中英

Access value from previous row pandas dataframe

I am currently writing some code to get stock quantities, and the code depends on whether items are moved from somewhere or to somewhere first. Therefore I need the value for the column in the dataframe which determines which action has been carried out (stock counted, stock moved, stock used etc.) from the previous row.

I have tried using df.shift() as I saw that in answer to another question, but that returns the entire column. Also I need it to be a string, I am hoping that the conversion will be possible using str() but I haven't been able to try it yet.

My current, simplified code is:

if row['Action'] == "Move From":
    if str(df['Action'].shift(1)) == "Move To": # Have tried with and without 1 argument
        # Rest of code
        print('Shift worked')

A sample df format would be something like:

Stock Location, Action, Total Quantity, Location Quantity
A1, Stock Count, 500, 500
A1, Move From, 500, 250
A2, Move To, 500, 250
A2, Stock Count, 500, 250
A1, Stock Count, 500, 250

Where the Total Quantity never changes because the stock is moving, but the quantities of the stock in locations A1 and A2 do change. The issue is that Move To doesn't always follow Move From , sometimes they are the other way around. To get the Factory Quantity, I sum up the quantities of all the locations which stock is stored in. I have been creating a Temp_Var equal to either the amount of stock that is moving, or the corresponding negative amount, depending on whether stock is moving from or to. However, the Temp_Var is only required for the first move, if the stock has already been moved the Temp_Var is not needed.

For additional clarity:

Using the above dataframe, during row 3, Total Quantity would equal the quantity in row A2 and an additional 250 in a temporary variable (as we don't yet know where it is moving to), then during row 4, Total Quantity would equal the quantities in row A1 and A2, not needing the temporary variable. Because sometimes Move To comes first, just by checking the 'Action' , I don't always know if I'll need a temp variable.

Realistically though the reasoning behind this is largely superfluous and makes the actually problem seem more confusing than it is. I just need to be able to check a value from the previous row

df['Action'].shift(1) creates a new column, so you need to do it before iterating through the dataframe, assigning it a new name:

df['Previous Action'] = df['Action'].shift(1) , and then refer to new column during iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM