Search code examples
pythonpandasloopsrangecell

Loop through cell range (Every 3 cells) and add ranking to it


The problem is I am trying to make a ranking for every 3 cells in that column using pandas. For example:

This is the outcome I want I have no idea how to make it.

I tried something like this:

for i in range(df.iloc[1:],df.iloc[,:],3):
counter = 0
i['item'] += counter + 1

The code is completely wrong, but I need help with the range and put df.iloc in the brackets in pandas.


Solution

  • Does this match the requirements ?

    import pandas as pd
    
    df = pd.DataFrame()
    df['Item'] = ['shoes','shoes','shoes','shirts','shirts','shirts']
    
    df2 = pd.DataFrame()
    for i, item in enumerate(df['Item'].unique(), 1):
      df2.loc[i-1,'rank'] = i
      df2.loc[i-1, 'Item'] = item
    
    df2['rank'] = df2['rank'].astype('int')
    print(df)
    print("\n")
    print(df2)
    
    df = df.merge(df2, on='Item', how='inner')
    print("\n")
    print(df)