pythonpython-3.xpandasdataframecolumnsorting

How to rewrite or add a column start from 1 in python


I have a dataframe like this and I want to re-rank Startup Rank starting from 1,2,3,4... to end. Or can I add a column start from 1,2,3,4.... and remove the Startup Rank column?

enter image description here


Solution

  • If you want to preserve the relative ranking, you can subtract the min value - 1:

    df['Startup Rank'] -= df['Startup Rank'].min()-1
    

    Or for a new column:

    df['new'] = df['Startup Rank'] - df['Startup Rank'].min() + 1
    del df['Startup Rank']
    

    If you want a brand new ranking top->down 1->n:

    df['Startup Rank'] = range(1, len(df)+1)