python - 循环删除 pandas 数据帧行

标签 python pandas dataframe row

我想循环删除行,直到到达时间值为04:30:00的行,然后停止删除过程。我该怎么做?

这是我的数据示例:

ticker  date    time    vol     vwap    open    high    low close
0   AACG    2022-01-06  04:07:00    242 2.0400  2.04    2.04    2.04    2.04
1   AACG    2022-01-06  04:08:00    427 2.0858  2.06    2.10    2.06    2.10
2   AACG    2022-01-06  04:09:00    906 2.1098  2.10    2.11    2.10    2.11
3   AACG    2022-01-06  04:16:00    186 2.1108  2.12    2.12    2.10    2.10
4   AACG    2022-01-06  04:30:00    237 2.0584  2.06    2.06    2.06    2.06
5   AACG    2022-01-06  04:31:00    700 2.1098  2.10    2.11    2.10    2.11

我尝试了这个,但它没有显示任何内容发生了变化:

row = 0
while df['time'].values[row] == datetime.time(4, 30) == False:
    print(df['time'].values[row])
    df.drop(row, axis=0, inplace=True)
    row = row + 1

这是df.info():

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 12 columns):
ticker    10 non-null object
date      10 non-null object
time      10 non-null object
vol       10 non-null int64
vwap      10 non-null float64
open      10 non-null float64
high      10 non-null float64
low       10 non-null float64
close     10 non-null float64
lbh       10 non-null int64
lah       10 non-null int64
trades    10 non-null int64
dtypes: float64(5), int64(4), object(3)
memory usage: 1.1+ KB

更新:再次感谢大家的帮助。

df[df['time'] >= datetime.time(4, 30)] 帮助我删除了不必要的行。

最佳答案

您可以使用 bool 掩码来切片数据。如果您的 df['time'] 是 datetime.time 对象,那么您可以简单地对 df 进行切片:

out = df[df['time'] > datetime.time(4,30)]

输出:

  ticker        date      time  vol    vwap  open  high  low  close
5   AACG  2022-01-06  04:31:00  700  2.1098   2.1  2.11  2.1   2.11

关于python - 循环删除 pandas 数据帧行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70687282/

相关文章:

python - 替换数据框中的重复值

python - 从文件创建句子列表并将其添加到数据框中

python - 在多索引数据帧上突出显示最大/最小值 - Pandas

python - 为什么不总是将 psyco 用于 Python 代码?

python - 为什么 Python 中的 mmap 实现为共享库?

python - 用 Python 编写基于套接字的服务器,推荐策略?

python - 连接数据帧时填写默认值

python - 如何将数据帧的每一行传递给数组

python - 使用 groupby 删除 Pandas 数据框中的异常值

Python - 索引超出范围错误