Create a new Dataframe based on conditions from another Dataframe for loop

create new dataframe from existing dataframe pandas
pandas create new column based on multiple condition
pandas create new column based on condition
pandas iterate over rows and create new column
pandas filter rows by condition
pandas select rows by multiple conditions
create pandas column with new values based on values in other columns
pandas set column value based on condition

Working with 2017 NFL Quarterback Data, looking to put the top 10 qbs each week in a dataframe (along with the rest of the data).

qb = {'week': [1, 1, 1, 2, 2, 2], 'qb': ['Rodgers', 'Brady', 'Wilson', 'Rodgers', 'Brady', 'Wilson'], 'pts': [30, 24, 20, 31, 20, 26]}

qb_df = pd.DataFrame(data=qb)

week    qb        pts
1       Rodgers   30
1       Brady     24
1       Wilson    20
2       Rodgers   31
2       Brady     20
3       Wilson    26

For this sake looking to return the top 2 from each week into a new dataframe.

week    qb        pts
1       Rodgers   30
1       Brady     24
2       Rodgers   31
2       Wilson    26

I tried a for loop that works as far as getting the data, but can't figure out to put it in a dataframe

top10_17 = pd.DataFrame()
for i in range(1, 18):
    i_17 = qb_2017.loc[qb_2017['Week'] == i].sort_values('FantasyPoints', ascending=False)[:10]
    top10_17 = pd.concat(i_17)

Used range(1,18) for the 17 weeks in an NFL season

IIUC sort_values with groupby + head

df.sort_values('pts',ascending=False).groupby('week').head(2).sort_values('week')
Out[49]: 
   pts       qb  week
0   30  Rodgers     1
1   24    Brady     1
3   31  Rodgers     2
5   26   Wilson     2

Python, While operating on data, there could be instances where we would like to add a column based on some condition. There does not exist any library function to  Selecting rows based on particular column value using '>', '=', '=', '<=', '!=' operator. Code #1 : Selecting all the rows from the given dataframe in which ‘Percentage’ is greater than 80 using basic method. # importing pandas. import pandas as pd.

grouped = qb_df.groupby('week')
print(grouped.head(2))

This assumes your list is sorted, which can be done with pandas.sort_values()

Selecting rows in pandas DataFrame based on conditions , Different ways to iterate over rows in Pandas Dataframe · Python | Delete rows/​columns from DataFrame using Pandas.drop() · Create a new column in Pandas​  Create a column using for loop in Pandas Dataframe Let’s see how to create a column in pandas dataframe using for loop. Such operation is needed sometimes when we need to process the data of dataframe created earlier for that purpose, we need this type of computation so we can process the existing data and make a separate column to store the

You could also do this:

qb_df.set_index('qb').groupby('week')['pts'].nlargest(2)

week  qb     
1     Rodgers    30
      Brady      24
2     Rodgers    31
      Wilson     26
Name: pts, dtype: int64

If format is really important to stay constant:

qb_df.set_index('qb').groupby('week')['pts'].nlargest(2).reset_index()

week       qb  pts
0     1  Rodgers   30
1     1    Brady   24
2     2  Rodgers   31
3     2   Wilson   26

Create new data frames from existing data frame based on unique , Create new data frames from existing data frame based on unique column values through the original data set and append in new values based on criteria. i.e.​, is there a way I can use a built-in pandas function to create new 'id' During handling of the above exception, another exception occurred:  In this Python 3 Programming Tutorial 13 video I have talked about How to loop over dataframe & create new calculated column. This is a very useful functionality all the time you need for data pre

Loops and Functions in R, Make decisions with if and else statements; Use a for loop to repeat operations to make R do one thing when one condition is met, and another thing when a To get you started, here is code to create a data.frame where all recrods with NA Many functions you would commonly use are built, but you can create custom  Given a Dataframe containing data about an event, we would like to create a new column called ‘Discounted_Price’, which is calculated after applying a discount of 10% on the Ticket price. Solution #1: We can use DataFrame.apply () function to achieve this task. # importing pandas as pd. import pandas as pd. # Creating the DataFrame.

Different ways to iterate over rows in a Pandas Dataframe , In total, I compared 8 methods to generate a new column of values based on an existing column (requires a single iteration on the entire column/  A data frame is a list of vectors which are of equal length. A matrix contains only one type of data, while a data frame accepts different data types (numeric, character, factor, etc.). We can create a data frame by passing the variable a,b,c,d into the data.frame () function. We can name the columns with name () and simply specify the name of

Tutorial: Advanced For Loops in Python – Dataquest, If you've already mastered the basics of iterating through Python lists, take it to the In addition to lists and tuples, dictionaries are another common Python data type A two-dimensional array is built up from a pair of one-dimensional arrays. For each row in our dataframe, we are creating a new label, and setting the row​  Create a function to assign letter grades. # Create a list to store the data grades = [] # For each row in the column, for row in df ['test_score']: # if more than a value, if row > 95: # Append a letter grade grades. append ('A') # else, if more than a value, elif row > 90: # Append a letter grade grades. append ('A-') # else, if more than a value, elif row > 85: # Append a letter grade