简体   繁体   中英

How do I check for a specific ticker string inside my dataframe with a column name of Name and return if it is found in the dataframe?

I need to check if the input of 'ticker' is inside of this dataframe with 'Name' as the column name and if I do stock_final.query("Name == 'AMZN'"), it works. I am unsure what the value of ticker is because it is input from a user. I need to correct this my_tick function to return the ticker if it is in the dataframe, otherwise have an error message.

参考问题

You can do this:

stock_final.query("Name == '{}'".format(ticker))

But if I understand correctly what you're really asking is whether a given ticker is in the column called "Name". That can be done better like this:

(stock_final["Name"] == ticker).any()

if the df.query() function does not find something in the column that macth, it will return a empty dataframe, in the begining is just a dataframe, but you can check if is empty by calling the df.empty property, for example

#some dataframe df
df.empty

This will return True if the dataframe is empty or False if it does not,

In your case, i recommend this

def my_tick(ticker):
    if not stock_final.query("Name == '{}'".format(ticker)).empty:
        return str(ticker)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM