如何更容易、更正确地向索引添加附加条件,以使代码更简单、更全面?

2024-10-05 10:45:29 发布

您现在位置:Python中文网/ 问答频道 /正文

上下文: 我正在尝试从数据集中获取满足以下条件的记录:

  • 如果时间戳在凌晨01:00-05:00之间
  • 如果“威胁”值为“3”

编辑: 显然,我可以通过执行“listCoord.index.hour”来打印所选用户的所有小时数,这些小时数是通过“listCoords”获得的。因为在熊猫中,小时是日期时间的一个属性。我在代码的条件语句中使用的这个:color=np.where((listCoords.index.hour == 6), 'red', '#5DBCD2')]

在这段代码中,我还想添加一个条件:listCoord.index.Thread=='3',这样我的代码就变成:

color=np.where((listCoords.index.hour == 6) & (listCoord.index.Thread == '3'), 'red', 'blue')]

但很明显,“线程”只是我的数据集中的一个列名,而不是pandas中的DateTime属性问题:如何将第二个条件添加到同一行?因此,我的代码变得更简单,涵盖范围更广




我的数据集
新建示例数据集points.csv:

Date/Time               Lat,                 Lon,                  Threat
2019-03-23 04:00:00,   -14.809489988279145,  26.191607774273443,    1
2019-03-23 04:00:00,   -14.792921094981814,  26.191716715339687,    2
2019-03-23 04:05:00,   -14.798684405083584,  26.162881454312586,    3
2019-03-23 04:10:00,   -14.80112670820822,   26.173830400821103,    2

已编辑-我的代码

   def update_graph(datePicked, selectedData, selectedLocation):
    zoom = 10.5
    latInitial = -14.873619
    lonInitial = 26.106700
    bearing = 0

    if selectedLocation:
        zoom = 13.0
        latInitial = list_of_fixed_sensors[selectedLocation]["lat"]
        lonInitial = list_of_fixed_sensors[selectedLocation]["lon"]

    date_picked = dt.strptime(datePicked, "%Y-%m-%d")
    monthPicked = date_picked.month - 4
    dayPicked = date_picked.day - 1
    listCoords = getLatLonColor(selectedData, monthPicked, dayPicked)

    # print(listCoords.index.Threat)

return go.Figure(
        data=[
            # Data for all observations based on date and time
            Scattermapbox(
                lat=listCoords["Lat"],
                lon=listCoords["Lon"],
                mode="markers",
                hoverinfo="text + lat + lon",
                text=listCoords.index.hour,
                marker=dict(
                    showscale=True,
                    # the color is decided by the time of detection.
                    # color=np.append(np.insert(listCoords.index.hour, 0, 0), 23),
                    color=np.where((listCoords.index.hour == 6), 'red', 'blue')]

Tags: of数据代码dateindexnpredwhere
1条回答
网友
1楼 · 发布于 2024-10-05 10:45:29

唯一的班轮是

df[(df['threat'] == 3) & df['Date/Time'].between_time('01:00', '05:00')]

假设df['Date/Time'].dtypedatetime,如果不使用pd.to_datetime

对于编辑案例,请使用:

color=np.where((listCoords.index.hour == 6) & (listCoord['Thread'] == '3'), 'red', 'blue')]

相关问题 更多 >

    热门问题