Home > database >  How to create new columns of last 5 sale price off in dataframe
How to create new columns of last 5 sale price off in dataframe

Time:12-11

I have a pandas data frame of sneakers sale, which looks like this, enter image description here

I added columns last1, ..., last5 indicating the last 5 sale prices of the sneakers and made them all None. I'm trying to update the values of these new columns using the 'Sale Price' column. This is my attempt to do so,

for index, row in df.iterrows():
    if (index==0):
        continue
    for i in range(index-1, -1, -1):
        if df['Sneaker Name'][index] == df['Sneaker Name'][i]:
            df['last5'][index] = df['last4'][i]
            df['last4'][index] = df['last3'][i]
            df['last3'][index] = df['last2'][i]
            df['last2'][index] = df['last1'][i]
            df['last1'][index] = df['Sale Price'][i]
            continue
    if (index == 100):
        break

When I ran this, I got a warning, A value is trying to be set on a copy of a slice from a DataFrame

and the result is also wrong. Does anyone know what I did wrong?

Also, this is the expected output, enter image description here

CodePudding user response:

Use this instead of for loop, if you have rows sorted:

df['last1'] = df['Sale Price'].shift(1)
df['last2'] = df['last1'].shift(1)
df['last3'] = df['last2'].shift(1)
df['last4'] = df['last3'].shift(1)
df['last5'] = df['last4'].shift(1)
  • Related