Python 如何从中的索引列中选择行

Python 如何从中的索引列中选择行,python,pandas,numpy,indexing,Python,Pandas,Numpy,Indexing,我想使用for循环查找基于df中另一列数据的连续时间段,即时间段(使用开始和结束时间戳定义),其中数据>20。 在df中,时间戳作为索引。我认为问题在于,在循环中,我没有正确指定从数据帧的索引列中选择行 循环的: for i in range(len(df3)): if i >0: activities = [] start_time = None if (df.loc[i, 'data'

我想使用
for循环
查找基于
df
中另一列
数据
的连续时间段,即时间段(使用开始和结束时间戳定义),其中
数据
>20。 在
df
中,
时间戳
作为索引。我认为问题在于,在循环中,我没有正确指定从数据帧的索引列中选择行

循环的

for i in range(len(df3)): 
    if i >0:

        activities = []          
        start_time = None          

        if (df.loc[i, 'data'] >= 20):                                   

            if start_time == None:   
                start_time = df.loc[i, 'timestamp']
        else:

            if start_time != None:
                end_time = df.loc[i-1, 'timestamp']

                duration = (end_time - start_time).seconds
                activities.append((duration, start_time, end_time))
                start_time = None 

return activities
df

                        id      timestamp               data    Date        sig     events
timestamp                           
2020-01-15 06:12:49.213 40250   2020-01-15 06:12:49.213 20.0    2020-01-15  -1.0    1.0
2020-01-15 06:12:49.313 40251   2020-01-15 06:12:49.313 19.5    2020-01-15  1.0     0.0
2020-01-15 08:05:10.083 40256   2020-01-15 08:05:10.083 20.0    2020-01-15  1.0     0.0
它返回:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-9853026603d5> in <module>()
      9 
     10 
---> 11         if (df.loc[i, 'data'] >= 20):                                   
     12 
     13             if start_time == None:

7 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in _invalid_indexer(self, form, key)
   3074         """
   3075         raise TypeError(
-> 3076             f"cannot do {form} indexing on {type(self)} with these "
   3077             f"indexers [{key}] of {type(key)}"
   3078         )

TypeError: cannot do index indexing on <class 'pandas.core.indexes.datetimes.DatetimeIndex'> with these indexers [1] of <class 'int'>
但也有同样的错误:

  File "<ipython-input-24-d78e4605aebe>", line 31
    return activities
                            ^
SyntaxError: 'return' outside function
文件“”,第31行
返回活动
^
SyntaxError:函数外部的“return”

loc
用于文本,而不是基于整数的索引,请改用
iloc
。更改:

if (df.loc[i, 'data'] >= 20):

这同样适用于其他
loc
s,如
df.loc[i,'timestamp']

编辑:

更好的方法是不使用for循环

  • 开始时间
    时间戳
  • end\u time
    是前一个的
    时间戳
  • duration
    是以秒为单位的差值
  • 这一进程将是:

    # Assign previous record's timestamp as end time
    df['end_time'] = df['timestamp'].shift(1)
    
    df['duration'] = df.apply(lambda x: (x['end_time'] -
                                         x['timestamp']).seconds, axis=1)
    

    你好,谢谢你的回答。它返回
    ValueError:序列的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all()。
    你知道这是什么意思吗?是的,这意味着
    iloc
    返回了一个序列,但你想要将单个值作为float/integer与
    20
    进行比较,请检查我所做的编辑。谢谢,这似乎已经删除了以前的错误!但是它返回了'File',第31行return activities^ SyntaxError:'return'在函数外部',尽管我多次更改了缩进。你知道我怎样才能得到
    活动
    表,每个活动都有
    开始时间
    结束时间
    ?你好,jcali,这是个好主意。我自己用你编辑的代码做了一些尝试,但不幸的是没有成功,可能是因为我还不熟悉编码。你能把全部代码加进去吗?非常感谢。这实际上是全部代码,发布您看到的错误,我可以帮助您。
    if (df.iloc[i].data >= 20):
    
    # Assign previous record's timestamp as end time
    df['end_time'] = df['timestamp'].shift(1)
    
    df['duration'] = df.apply(lambda x: (x['end_time'] -
                                         x['timestamp']).seconds, axis=1)