suzanne chen
suzanne chen

Reputation: 155

How do I put input into a python df?

enter image description here

Is it possible to put a user input into a df? Here I am asking user to select the Town they are interested to find home prices, and return users with the lowest and highest home prices.

  1. I have hardcoded the group "YISHUN" > When this is supposed to be user input
  2. Also, the results are sorted pricing. How do I take the two values - the lowest and the highest?

Thank you so much!

sorted_df = df.sort_values("resale_price", ascending=True)
grouped_df = sorted_df.groupby("town")
grouped_df = grouped_df.get_group("YISHUN")
grouped_df = grouped_df[['resale_price']]
print(grouped_df)

Upvotes: 2

Views: 176

Answers (2)

Amit Amola
Amit Amola

Reputation: 2510

It's actually really simple:

def get_hi_low(df, val):
    dummy_df = df[df['town']==val]
    return max(dummy_df['resale_price'].values), min(dummy_df['resale_price'].values)

val = input("Enter town name: ")
high, low = get_hi_low(df, val)

print(f'For town {val}, the highest value is: {high} and low is {low}')

Check if this works.

Edit: Creating this as a function has a lot of benefits. In fact, whenever possible, you should usually code using functions.

So let's say you just don't have one but many users. For example:

town_list = ['Town_A', 'Town_B', 'Town_C']

Now you can loop around all these:

for town in town_list:
    high, low = get_hi_low(df, town)
    print(f'For town {town}, the highest value is: {high} and low is {low}')

So now for each town, it will result in the high and low value of the resale price.

And since in your case it's a user input? Well you can do it this way too:

while True:
    town = input("Enter town name: ")
    
    if town=='exit':
        break

    high, low = get_hi_low(df, town)
    print(f'For town {town}, the highest value is: {high} and low is {low}')

In this case, user keep on inputting a town and for each case it gives a result. But remember code never stops in this case. The only case it will stop is when you input 'exit' and the loop ends. One last quick advice. This code will give error if the town name provided doesn't exist. Well for that case you can use try, except block. Well, look into what a try except is.

Hope this makes more sense. If you want to learn more about functions and even python extensively before jumping. I can suggest you some free courses and links to those.

Upvotes: 1

Manoj S Ramaswamy
Manoj S Ramaswamy

Reputation: 33

val = input("Enter column name: ")
print(df.groupby([val])['YEAR'].count())

Yes, you can. Please try to give input before invoking group function. The above is a sample. I just tried out and I found it working.

Upvotes: 0

Related Questions