查询 Pandas DataFrame 时出现 UndefinedVariableError

lbu*_*bug 9 python pandas

我正在尝试通过查询 pandas 中的值来创建图形DataFrame

在这一行:

data1 = [np.array(df.query('type == i')['continuous']
         for i in ('Type1', 'Type2', 'Type3', 'Type4')]
Run Code Online (Sandbox Code Playgroud)

我收到错误:

UndefinedVariableError: name 'i' is not defined
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

ali*_*i_m 13

i您的查询表达式

df.query('type == i')
Run Code Online (Sandbox Code Playgroud)

字面上就是字符串'i'。由于它周围没有额外的引号,pandas 将其解释为您的 中另一列的名称DataFrame,即它查找以下情况

df['type'] == df['i']
Run Code Online (Sandbox Code Playgroud)

由于没有i列,您将获得一个UndefinedVariableError.

看起来您打算查询type列中的值在哪里等于名为 的字符串变量i,即 where

df['type'] == 'Type1'
df['type'] == 'Type2' # etc.
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您需要将字符串实际插入i到查询表达式中:

df.query('type == "%s"' % i)
Run Code Online (Sandbox Code Playgroud)

额外的一套报价是必要的,如果'Type1''Type2'等是的中type柱,但如果他们在数据帧的其他列的名称。