Pandas/Geopandas 与蒙版选择合并

Pandas/Geopandas Merge with a mask selection

我通常使用 Arcpy,但正在尝试了解更多 pandas/geopandas 用途。我有一个蒙版应用于 csv table 和一个我想合并在一起的 shapefile,以便根据特定字段找到两者之间的匹配项。

但是,当我尝试将它们合并在一起时,出现错误“Dataframe 的真值不明确”。如何合并屏蔽的数据框?我在下面包含了创建掩码的代码段(利用两个日期变量和一个日期字段)和使用位置字段(每个数据帧上的不同名称)的合并。

我需要做什么来操纵掩码数据帧使其在掩码中正常运行?

    mask = (svc_df['createdate'] < curdate) & (svc_df['createdate'] >= backdate)
    print(svc_df.loc[mask])
    # Detect the sub-dataframe and then assign to a new dataframe
    sel_df = svc_df.loc[mask]
    #Create a geodf from alabama services
    al_gdf = geopandas.read_file(alSvc_shp)
    al_merge = al_gdf.merge(al_gdf, sel_df, left_on="Location", right_on="sketch_LOC")
  • 已从您的代码中合成了一个 MWE。生成和数据框和地理数据框
  • 你有一个错误:
al_merge = al_gdf.merge(al_gdf, sel_df, left_on="Location", right_on="sketch_LOC")
  • 使用了dataframe.merge()而不是pd.merge()因此只有一个数据帧应该作为参数传递
  • 下面是完整的工作示例
import pandas as pd
import numpy as np
import geopandas as gpd

# synthesize
svc_df = pd.DataFrame(
    {
        "createdate": pd.date_range("1-mar-2022", periods=30),
        "sketch_LOC": np.random.choice(["CHN", "USA", "IND", "JPN", "DEU"], 30),
    }
)
curdate = pd.to_datetime("today")
backdate = curdate - pd.Timedelta("5 days")

mask = (svc_df["createdate"] < curdate) & (svc_df["createdate"] >= backdate)
print(svc_df.loc[mask])
# Detect the sub-dataframe and then assign to a new dataframe
sel_df = svc_df.loc[mask]
# Create a geodf from alabama services
# al_gdf = geopandas.read_file(alSvc_shp)
# synthesize
al_gdf = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")).assign(
    Location=lambda d: d["iso_a3"]
)
al_merge = al_gdf.merge(sel_df, left_on="Location", right_on="sketch_LOC")