【问题标题】:Delete all (hourly) day entries per row based on a daily table in python根据python中的每日表删除每行的所有(每小时)日条目
【发布时间】:2020-04-20 13:58:49
【问题描述】:

我有一个带有 datetime64[ns] 对象的数据框,该对象具有格式,所以我有每小时基数的数据:

Datum                    Values
2020-01-01 00:00:00      1
2020-01-01 01:00:00      10
....
2020-02-28 00:00:00     5
2020-03-01 00:00:00     4

还有一张有关闭日期的表格,也在datetime64[ns] 列中,格式是这样的,所以我只有一个日期格式:

Dates
2020-02-28
2020-02-29
....

如何删除第一个数据帧 df 中的所有日期,这些天数出现在第二个数据帧 Dates 中?所以 df 是:

2020-01-01 00:00:00      1
2020-01-01 01:00:00      10
....
2020-03-01 00:00:00      4

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用Series.dt.floortimes 设置为0,因此可以在boolean indexing 中使用带有反转掩码的Series.isin 过滤:

    df['Datum'] = pd.to_datetime(df['Datum'])
    df1['Dates'] = pd.to_datetime(df1['Dates'])
    
    df = df[~df['Datum'].dt.floor('d').isin(df1['Dates'])]
    print (df)
                    Datum  Values
    0 2020-01-01 00:00:00       1
    1 2020-01-01 01:00:00      10
    3 2020-03-01 00:00:00       4
    

    编辑:对于标志列,通过 Series.viewSeries.astype 将掩码转换为整数:

    df['flag'] = df['Datum'].dt.floor('d').isin(df1['Dates']).view('i1')
    #alternative
    #df['flag'] = df['Datum'].dt.floor('d').isin(df1['Dates']).astype('int')
    print (df)
                    Datum  Values  flag
    0 2020-01-01 00:00:00       1     0
    1 2020-01-01 01:00:00      10     0
    2 2020-02-28 00:00:00       5     1
    3 2020-03-01 00:00:00       4     0
    

    【讨论】:

    • thx,如何在数据框 df 中添加一个 0(不是删除日期)和 1(删除日期)的列,以便我有一个标记而不是删除行?
    【解决方案2】:

    考虑您添加的评论

    string of the Dates in df1
    c="|".join(df1.Dates.values)
    c
    

    将基准强制转换为日期时间

    df['Datum']=pd.to_datetime(df['Datum'])
    df.dtypes
    

    Extract Datum as Dates ,dtype string

    df.set_index(df['Datum'],inplace=True)
    df['Dates']=df.index.date.astype(str)
    

    两者中的布尔选择日期

    m=df.Dates.str.contains(c)
    m
    

    将包含日期标记为 0,将排除日期标记为 1

    df['drop']=np.where(m,0,1)
    df
    

    删除不需要的行

    df.reset_index(drop=True).drop(columns=['Dates'])
    

    结果

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 2020-03-13
      • 2020-05-25
      • 2017-04-04
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      相关资源
      最近更新 更多