Home > Blockchain >  How can I create a function to subtract values from a df by calling upon team names?
How can I create a function to subtract values from a df by calling upon team names?

Time:12-30

data = {
'Team': \['SF','B','NE'\],
'O_Yppt': \[14.5, 14.4, 14.4\],
'D_Yppt': \[18.9, 18.1, 16.5\],
'Total_yppt': \[4.4, 3.7, 1.5\]}

NFL_YPPT = pd.DataFrame(data)

The data I am using has a couple more columns in between, but this is where I am stuck. I tried defining a few functions and using iloc to focus on certain rows to apply subtraction but no luck. I couldn't find anything on youtube or blogs either.

The function I envisioned would take two team names for example 'SF' and 'NE' and return simple subtraction of each total_yppt resulting in 2.9.

Again, I am still novice with Python so I'm not sure exactly how to do this, but I know this program is powerful and I'm sure there's multiple solutions. If you can explain how to solve this small problem of mines or point me to some juicy learning resources, it would be greatly appreciated.

CodePudding user response:

When it comes to coding there will be nothing direct...Have to connect dots & solve step by step. Simply set index as team and filter team based on index names based on user input.

def diff(team):
    
    NFL_YPPT.set_index('Team', inplace=True)
    Filter_df  = NFL_YPPT[NFL_YPPT.index.isin(team)]
    return Filter_df.diff(-1)['Total_yppt'].tolist()[0]

Driver code #

print(diff(['SF','NE']))

output #

2.9000000000000004

CodePudding user response:

You could do it in one line using:

x = NFL_YPPT['Total_yppt'][NFL_YPPT['Team'].isin(['SF', 'NE'])].diff(-1).values[0]

print(x)

2.9000000000000004

Note that \ not needed in your data definition

or maybe more simply get each value and then just subtract

x1 = NFL_YPPT['Total_yppt'][NFL_YPPT['Team'] == 'SF'].values[0]
x2 = NFL_YPPT['Total_yppt'][NFL_YPPT['Team'] == 'NE'].values[0]

print(x1 - x2)

  • Related