Search code examples
pythonpandasdata-sciencefinance

find nlargest ID for a value for each date


I am looking for the 10 IDs that have the highest a value at each date.

df

for date in df:
    a = df.nlargest(10, ['a'])
    Top_performer.append(a[['ID','Renta','Date']])

as output I would like the IDs and their 'renta' for each date

I'm bothering you for something pretty simple I guess but I'm stuck! thanks


Solution

  • This is a possible solution:

    1. Groupby date
    2. On each date, find the 10 largest values for "Renta"
    3. Give a proper format to the output

    Code:

    >>> df.groupby("Date").apply(lambda x: x.nlargest(10, "Renta")).reset_index(drop=True))