Home > Blockchain >  How to pass a list of strings one by one to query() using a function in python?
How to pass a list of strings one by one to query() using a function in python?

Time:11-29

I want to pass every unique value of a column to a user-defined function one by one and get the results. the unique values are strings and the function is based on query(). below is how I did it and it's not working. i.e I can not pass the 'u' to the query. what is wrong with this code? thx in advance

def score_effect(platform):
    df = data.query('platform=="p"')[['sum_of_sales', 'critic_score', 'user_score']]
    plt.figure(figsize=(17,10))
    plt.subplot(1,2,1)
    sns.scatterplot(data=df, x='sum_of_sales', y='critic_score')
    plt.subplot(1,2,2)
    sns.scatterplot(data=df, x='sum_of_sales', y='user_score')
    plt.show()
 
    critic_corr = df.corr().iloc[0,1]
    user_corr = df.corr().iloc[0,2]
    print('Correlation between critic-reviews and sales =', critic_corr)
    print('Correlation between user-reviews and sales =', user_corr)
 
    if critic_corr>0.7:
 
        print('There is a POSITIVE correlation between  critic-reviews and sales')
    else:
        print('There is no significant correlation between critic-reviews and sales')
    if  user_corr>0.7:
        print('There is a POSITIVE correlation between  user-reviews and sales')
    else:
        print('There is no significant correlation between user-reviews and sales')
 
 
 
for p in data['platform'].unique():
    print('Result for:', p)
    score_effect(p)
    print('***************************')

CodePudding user response:

It looks like you should replace

data.query('platform=="p"')

with

data.query('platform == @platform')

for starters. The argument to your function is platform, not p. p is the variable name in your for loop but the function scope is different, so your function doesn't have access to p.

You should also prefix your variable with an @ sign as I did above to let pandas know that it's a variable and not the string literal "platform". From the documentation:

You can refer to variables in the environment by prefixing them with an ‘@’ character like @a b.

  • Related