【问题标题】:How to do multi logic value comparisons between dataframes?如何在数据帧之间进行多逻辑值比较?
【发布时间】:2019-02-09 19:37:22
【问题描述】:

我有两个这样的数据框:

df1:

Email      DateTimeCompleted
2@2.com    2019-02-09T01:34:44.591Z

df2:

Email         DateTimeCompleted
b@b.com       2019-01-29T01:34:44.591Z
2@2.com       2018-01-29T01:34:44.591Z

如何在 df2 中查找 Email 值并比较 DateTimeCompleted 大于 TODAY(减去)90 天的位置并将 df1 行数据附加到 df2 中?有时添加 df2 可以是空的,如果这会有所不同。

df2 更新后如下所示:

 Email         DateTimeCompleted
b@b.com       2019-01-29T01:34:44.591Z
2@2.com       2018-01-29T01:34:44.591Z
2@2.com       2019-02-09T01:34:44.591Z

我试过了:

from datetime import date    

if df1.Email in df2.Email & df2.DateTimeCompleted >= date.today()-90 :
    print('true')

我得到错误:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

Also tried:

if df2.Email.str.contains(df1.Email.iat[0]):
    print('true')

got error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    您可以执行以下操作:
    1. merge keycolumns Email 上的两个数据框,因此您知道哪些行包含在两个数据框中。
    2.过滤大于today - 90days的行
    3. 使用pd.concat 将数据帧连接到final

    代码:

    # Merge dataframes together
    df3 = pd.merge(df1, df2, on=['Email'], suffixes=['', '_2'])
    
    # Filter the rows
    df3 = df3[df3.DateTimeCompleted > (dt.today() - timedelta(90))]
    
    # Drop the column we dont need
    df3.drop(['DateTimeCompleted_2'], axis=1, inplace=True)
    
    # Create final dataframe by concatting
    df_final = pd.concat([df2, df3], ignore_index=True)
    
        Email   DateTimeCompleted
    0   b@b.com 2019-01-29 01:34:44.591
    1   2@2.com 2018-01-29 01:34:44.591
    2   2@2.com 2019-02-09 01:34:44.591
    

    【讨论】:

      【解决方案2】:

      我写了一个函数来做以下事情

      函数接受参数

      mailid, dataframe1, dataframe2

      def process(mailid,df1,df2):
          if mailid in df2.Email.values:
              b = df1.loc[df1.Email==mailid,"DateTimeCompleted"].head(1)
              if((~b.empty) or (int(((pd.to_datetime('today'))-(pd.to_datetime(b))).astype('timedelta64[D]')) >90)):
                  df1 = pd.concat([df1, pd.DataFrame([[mailid,b[0]]],columns=['Email','DateTimeCompleted'])],axis=0)
                  print("Added the row")
              else:
                  print("Condition failed")
                  print("False")
          else:
              print("The mail is not there in dataframe")
          return df1
      

      【讨论】:

        猜你喜欢
        • 2016-09-05
        • 2016-08-26
        • 2020-05-13
        • 1970-01-01
        • 2021-10-03
        • 1970-01-01
        • 2014-03-13
        • 2016-10-17
        • 1970-01-01
        相关资源
        最近更新 更多