You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将字符串列表逐值传递给自定义函数内的query()方法

问题排查与修复方案

核心错误点

  1. query()方法没有正确引用传入参数:你当前的query语句是固定匹配字符串"p",而非函数接收的platform参数值,且代码中残留了HTML转义字符("对应双引号、>对应大于号),无法正常解析。
  2. pandas的query()方法若要引用外部作用域的变量,需要给变量加@前缀标识,不需要额外手动加引号匹配字符串类型。

修正后代码

def score_effect(platform):
    # 关键修改:用@引用外部传入的platform参数
    df = data.query('platform == @platform')[['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('***************************')

可选替代方案

如果更习惯用f字符串拼接,也可以写成下面的形式,注意内层要加单引号包裹字符串值:
df = data.query(f'platform == "{platform}"')[['sum_of_sales', 'critic_score', 'user_score']]
更推荐使用@变量的写法,不需要处理引号嵌套问题,也能避免特殊字符导致的语法错误

内容的提问来源于stack exchange,提问作者darzgir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:15:03