SQL + While 循环中的熊猫

发布于 2025-01-21 02:18:04 字数 810 浏览 4 评论 0原文

我正在运行SQL查询,并将结果保存到Pandas DF。我的条件是至少获得n行号。我正在使用while-loop运行并更新查询,直到满足条件为止。

df = pd.DataFrame({})
rows = df.shape[0]

# search radius - miles to meters
radius = 1.5*1609

# Between 20 to 30 results in comps set
while rows <= 30:

    # Run query
    query = '''
            select * from schema_name.table1
            where st_distance_sphere(Point({},{}), coords) <= {};
            '''.format(Long, Lat, radius)

    df = pd.read_sql(query, con)

    rows = df.shape[0]

    if rows >= 20:
        break
    else:
        radius = radius * 2

基本上,查询正在寻找point坐标的指定半径内的行。我希望这将返回20-30行,但是,结果是100行。我很可能在这里错过了一些东西,并试图调试发生的事情。

使用一段循环如何将结果限制为20-30行?如果返回的行是&lt; 20,则想法是扩展半径。

I am running a SQL query and saving the results to a pandas DF. My condition is to obtain at least N number of rows. I am using a while-loop to run and update the query until the condition is met.

df = pd.DataFrame({})
rows = df.shape[0]

# search radius - miles to meters
radius = 1.5*1609

# Between 20 to 30 results in comps set
while rows <= 30:

    # Run query
    query = '''
            select * from schema_name.table1
            where st_distance_sphere(Point({},{}), coords) <= {};
            '''.format(Long, Lat, radius)

    df = pd.read_sql(query, con)

    rows = df.shape[0]

    if rows >= 20:
        break
    else:
        radius = radius * 2

Basically, the query is looking for rows that are within the specified radius of the POINT coordinates. I'd expect this to return 20-30 rows, however, the result is 100 rows. I am likely missing something here and trying to debug what's going on.

Using a while loop how do I restrict the results to 20-30 rows? The idea is to expand the radius if the rows returned are <20.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

掩耳倾听 2025-01-28 02:18:04

您可以添加一个限制子句以限制查询返回的行数。

select * 
from schema_name.table1 
where st_distance_sphere(Point({},{}), coords) <= {}
LIMIT 30;

您还可以在计算的距离上添加订单,然后获取30个最接近的点。

You can add a LIMIT clause to restrict the number of rows returned by the query.

select * 
from schema_name.table1 
where st_distance_sphere(Point({},{}), coords) <= {}
LIMIT 30;

You can also add an ORDER BY for the distance you are calculating and then get the 30 closest points.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文