简体   繁体   English

基于时间戳小时删除 DataFrame 中的行

[英]Droping rows in DataFrame based on Timestamp Hour

I'm attempting to drop rows in a DataFrame that has a datetime index column.我正在尝试删除具有日期时间索引列的 DataFrame 中的行。 I'm getting an error for comparing a str to an int using <.使用 < 比较 str 和 int 时出现错误。

The code I'm running is below.我正在运行的代码如下。

def clean(df):
    for i in range(len(df)):
        hour = pd.Timestamp(df.index[i]).hour
        minute = pd.Timestamp(df.index[i]).minute
        if hour < 8 and minute < 45:
            df.drop(axis=1, index=i, inplace=True)

Which results in the error: TypeError: '<' not supported between instances of 'str' and 'int'这导致错误: TypeError: '<' not supported between instances of 'str' and 'int'

If I write a separate line: type(pd.Timestamp(df.index[i]).hour) it returns <class 'int'>如果我单独写一行: type(pd.Timestamp(df.index[i]).hour)它返回<class 'int'>

I can perform math like hour += 1 but when comparing the hour or minute the if statement returns the error.我可以执行像hour += 1这样的数学运算,但是在比较小时或分钟时,if 语句返回错误。 Changing the code to hour = int(pd.Timestamp(df.index[i]).hour) also doesn't help.将代码更改为hour = int(pd.Timestamp(df.index[i]).hour)也无济于事。

Thank you谢谢

您可以制作一个掩码指定要保留的行,而不是循环遍历行(这会很慢),然后让pandas给您一个(更快的)答案:

df = df[(df.index.hour >=8) | (df.index.minute >= 45)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM