循环删除熊猫数据帧行



我想循环删除行,直到到达时间值为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)]帮助我删除了不必要的行。

您可以使用布尔掩码对数据进行切片。如果你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

不要循环,而是切片。你可以为此使用掩码(这里用布尔数组和cummax生成):

df[df['time'].eq('04:30:00').cummax()]

输出:

ticker        date      time  vol    vwap  open  high   low  close
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

如果还想排除匹配的行:

df[df['time'].eq('04:30:00').shift(fill_value=False).cummax()]

如果将time列转换为TimedeltaIndex,则不需要在此处循环:

out = df[~pd.to_timedelta(df['time']).lt('04:30:00')]
print(out)
# Output
ticker        date      time         vol  vwap  open  high  low close
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

行得通吗?

from datetime import time
out = df[df['time'] >= time(4, 30)]
print(out)
# Output:
ticker        date      time         vol  vwap  open  high  low close
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
# Info
print(df['time'].iloc[0])
# datetime.time(4, 7)

此解决方案

  1. "date"列和"time"列合并为一个新的datetime.datetime列,
  2. 搜索给定时间的第一次出现,以及
  3. 删除给定时间中第一次出现的行,但不包括这些行。

  • 如果未找到给定的时间,则不会删除任何内容,因为row_ix_of_first_occurrence等于0
  • 该解决方案适用于整数索引和字符串索引。
from io import StringIO
from datetime import datetime
import pandas as pd

def parse_date_time(date: str, time_24: str) -> datetime:
return datetime.strptime(" ".join((date, time_24)), "%Y-%m-%d %H:%M:%S")

df = pd.read_csv(
StringIO("""ticker  date    time    vol     vwap    open    high    low close
AACG    2022-01-06  04:07:00    242 2.0400  2.04    2.04    2.04    2.04
AACG    2022-01-06  04:08:00    427 2.0858  2.06    2.10    2.06    2.10
AACG    2022-01-06  04:09:00    906 2.1098  2.10    2.11    2.10    2.11
AACG    2022-01-06  04:16:00    186 2.1108  2.12    2.12    2.10    2.10
AACG    2022-01-06  04:30:00    237 2.0584  2.06    2.06    2.06    2.06
AACG    2022-01-06  04:31:00    700 2.1098  2.10    2.11    2.10    2.11"""),
delim_whitespace=True,
parse_dates={"datetime": ["date", "time"]},
date_parser=parse_date_time,
index_col=False,
header=0,
engine="python",
keep_date_col=False,
)
print(f"DataFrame initially:n{df.to_string()}n")
is_given_time = (
(df["datetime"].dt.hour == 4)
& (df["datetime"].dt.minute == 30)
& (df["datetime"].dt.second == 0)
)
row_ix_of_first_occurrence = is_given_time.argmax()
row_ix_delete = df.index[:row_ix_of_first_occurrence]
df = df.drop(index=row_ix_delete)
print(f"DataFrame after filtering:n{df.to_string()}")

最新更新