python通过坐标过滤csv文件

bf1o4zei  于 2023-06-19  发布在  Python
关注(0)|答案(1)|浏览(156)

我需要根据坐标过滤一个区域的事故。ChatGPT说我应该这样做:

def filterAccidentsByBounds():
    # Filter bike accident DataFrame by the given bounds
    df_bikeAccidents_h = df_bikeAccidents.loc[
        (df_bikeAccidents['Latitude'] >= 52.302885) &
        (df_bikeAccidents['Latitude'] <= 52.453221) &
        (df_bikeAccidents['Longitude'] >= 9.584375) &
        (df_bikeAccidents['Longitude'] <= 9.902979)
    ]
    
    # Print the number of bike accidents in Hannover
    print("Number of bike accidents in Hannover:", len(df_bikeAccidents_h))
    
    return df_bikeAccidents_h

df_bikeAccidents_h = filterAccidentsByBounds()

但我想用一个if循环来实现它,像这样:

def filterAccidentsByBounds():
    #filter bike accident dataframe by the given bounds
    #df_bikeAccidents_h = ...
    #XGCSWGS84        YGCSWGS84
    #print number of bike accidents in Hannover
    
    # YOUR CODE HERE
    
    df_bikeAccidents_h = df_bikeAccidents
    if df[[XGCSWGS84]] <= 52.453221 and df[[XGCSWGS84]] >= 52.302885:
        if df[[YGCSWGS84]] <= 9.902979 and df[[YGCSWGS84]] >= 9.584375
    
    
    return df_bikeAccidents_h

df_bikeAccidents_h = filterAccidentsByBounds()

问题是我不知道在if循环中写什么。有人能帮我吗?
我试着用if循环通过坐标来过滤事故,但由于我缺乏python技能,我不知道在if语句中写些什么。

jexiocij

jexiocij1#

我建议你看看itertuples考虑下面的例子,假设我想要打印x和y,其中y大于或等于x,那么我可以这样做:

import pandas as pd
df = pd.DataFrame({"x":[1,2,3,4,5],"y":[5,4,3,2,1]})
for row in df.itertuples():
    if row.y >= row.x:
        print(row.x, row.y)

给出输出

相关问题