SK Singh
SK Singh

Reputation: 163

Iterating rows in Python

I want to first iterate through the item number and then for a particular item, I need to iterate through the week number. Main aim is to flag the week number of a each item in which there is inventory addition. I am newbie, so I am not aware of how to do double iteration. Data

Output will look like this

Output will be like this. The flag becomes one when the inventory for the current week is greater than the previous one.

Upvotes: 0

Views: 90

Answers (1)

niraj
niraj

Reputation: 18208

IIUC: You can try using .groupby item number followed by .shift in dataframe as following.

Suppose the original dataframe is as below:

   DIV_NBR  itm_nbr  WEEK_NO  DISTINCT_ITM_CNT  INVENTORY_IN_HAND
0       18    65874   201511               5.0             2925.0
1       18    65874   201512               5.0             2910.0
2       18    65874   201513               5.0             2961.0
3       19    65875   201511               5.0             2965.0
4       19    65875   201512               5.0             2971.0

Then:

# keep record of last week by grouping by item number and then using shift
df['LAST_WEEK'] = df.groupby('itm_nbr')['INVENTORY_IN_HAND'].shift()

# check if current inventory is greater than last week
df['Flag'] = (df['INVENTORY_IN_HAND'] - df['LAST_WEEK'])>0

# delete additional column
del df['LAST_WEEK']

# change flag int
df['Flag'] = df['Flag'].astype(int)

print(df)

Result:

   DIV_NBR  itm_nbr  WEEK_NO  DISTINCT_ITM_CNT  INVENTORY_IN_HAND  Flag
0       18    65874   201511               5.0             2925.0     0
1       18    65874   201512               5.0             2910.0     0
2       18    65874   201513               5.0             2961.0     1
3       19    65875   201511               5.0             2965.0     0
4       19    65875   201512               5.0             2971.0     1

Upvotes: 1

Related Questions