Jupyter Notebook Markdown单元格中Pandas查询含比较运算符报错问题
query and > Hey, I get exactly why this is tripping you up—Jupyter's inline Markdown variable parsing has a quirk when you mix HTML entities with Python code. Let's break down what's happening and fix it without having to pre-define variables in separate cells.
The Root Cause
When you used > instead of > in your query string, Jupyter doesn't translate that HTML entity back to the actual > operator when it runs the Python code inside {{ }}. Instead, it tries to execute > as part of the code, which is invalid Python syntax—hence the SyntaxError about only a single expression being allowed.
Solution 1: Just Use > Directly in the Query
Markdown only treats > as a blockquote when it's at the start of a line followed by a space. When it's inside the {{ }} inline code, it won't trigger that behavior. So you can safely write the actual > operator in your query:
This is a *larger* amount : {{df4.groupby(['customer_name'])['amount'].sum().reset_index().query('amount > 0')['amount'].sum()}} - let me explain further...
Run that Markdown cell, and it'll correctly compute the sum as 1002, just like you expected.
Solution 2: Replace query with a Lambda Filter (No > in Strings)
If you're still wary of Markdown parsing edge cases, you can rewrite the filtering part using a lambda expression instead of query. This keeps the comparison entirely within Python code, no string-based syntax to worry about:
This is a *larger* amount : {{df4.groupby(['customer_name'])['amount'].sum().reset_index()[lambda df: df['amount'] > 0]['amount'].sum()}} - let me explain further...
This works exactly the same way, avoiding any Markdown special character conflicts.
Quick Test with Your Data
Using your sample dataframe:
import pandas as pd dt = {'customer_name': ['a','a','b','b','c'], 'amount': [-1,-1,1,1,1000]} df4 = pd.DataFrame(data = dt)
Either solution will output:
This is a larger amount : 1002 - let me explain further...
内容的提问来源于stack exchange,提问作者alicook

