Bryan Koh
Bryan Koh

Reputation: 13

Python: How do I take two different column inputs from the user and return the value of another column?

enter image description here

Using the first row as an example, let's say the user types in Arsenal and Leicester City. How do I get the code to match the inputted teams to "home_team" and "away_team" in the table and finally return the value 'H' which is from the column 'result' ?

I tried doing

x = input("Enter Home Team: ") y = input("\nEnter Away Team: ")

def f(x,y): return df.loc[df['Col 1'] == x and df['Col 2'] == y, 'Col 3'].item()

But nothing turns up.

Upvotes: 1

Views: 20

Answers (1)

ScottC
ScottC

Reputation: 4105

Here is simplified and relevant version of your dataframe.
Say your dataframe is named (df):

import pandas as pd

df = pd.DataFrame({'home_team':['Arsenal', 'Watford', 'Chelsea'],
                   'away_team':['Leicester City','Liverpool','Burnley'],
                   'result':['H','D','A']})

Then you could extract the results from your dataframe in the way that you were trying to do it - like this:

# Function to extract result
def f(x,y): return df.loc[(df['home_team'] == x) & (df['away_team'] == y), ['result']]

# Get the teams from the user
x = input("Enter Home Team: ") 
y = input("\nEnter Away Team: ")

# Print the result
print(f(x,y))

And the output when you select Arsenal for the home team and Leicester City for the away team is:

  result
0      H

Upvotes: 0

Related Questions