【问题标题】:Finding the first row which stratifies two conditions in python data frame在python数据框中找到对两个条件进行分层的第一行
【发布时间】:2021-08-26 16:23:03
【问题描述】:

我有一个如下所示的数据框:

data frame

我想编写一个代码来定位与下一个点的距离小于 250 的点。当它找到该点时,搜索距离超过 250 且速度大于 5 的第一个点。 例如在样本数据集中,先找到第 7 行,然后定位到 250 多外,速度为 10.8 的第 10 行,返回第 10 行的索引 到目前为止我已经写了这段代码:

for i in (number+1 for number in range(data_gpd.index[-1]-1)):
if (data_gpd['distance'][i+1]< 250):

我不确定在这种情况之后我应该做什么。我曾考虑使用带有条件的“Next”语句,但我只能在一个条件下找到它用于列表理解。

非常感谢您的帮助,因为我是 python 新手,不确定哪种语法会更好

【问题讨论】:

    标签: python pandas if-statement next


    【解决方案1】:

    您可以使用 pandas 函数 loc 和相关条件来返回 pandas DataFrame。

    第一个条件:

    df['distance'] < 250
    

    第二个条件:

    df['speed'] > 5
    

    综合条件:

    (df['distance'] < 250) & (df['speed'] > 5)
    

    使用loc 和组合条件:

    df.loc[(df['distance'] < 250) & (df['speed'] > 5)]
    

    输入:

       time  location  distance   speed
    0   300      9071      9071  108.00
    1   300     18376      9304   11.00
    2   300     28006      9630  115.00
    3   200     30506      2500   45.00
    4   400     31606      1100    9.90
    5   500     31706       100    0.72
    6   150     31756        50    1.20
    7    20     31766        10    1.80
    8    50     31916       150   10.80
    

    输出:

       time  location  distance  speed
    8    50     31916       150   10.8
    

    【讨论】:

      猜你喜欢
      • 2015-12-24
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多