【问题标题】:Pandas date and text condition熊猫日期和文本条件
【发布时间】:2018-04-10 21:19:02
【问题描述】:

给定一个df:

Date1                   Text1    
2018-03-20 00:00:00     abc       
2018-04-01 00:00:00     abc
2018-01-01 00:00:00     abc
2018-04-01 00:00:00     xyz
                        abc

我的目标是添加一个新列,其中: 如果 text = "abc" 并且 Date1 从现在开始还有 90 天,那么 "New" 输出将是:

Date1                   Text1    NewText
2018-03-20 00:00:00     abc      New
2018-04-01 00:00:00     abc      New
2018-01-01 00:00:00     abc
2018-04-01 00:00:00     xyz
                        abc

这就是我所拥有的:

days90 = date.today() - timedelta(90)

df['NewText'] = np.where(df['Text1'] = "abc" & df['Date1'] < pd.to_datetime(days90), "New", np.nan)

但是,我总是遇到错误。
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

有什么建议吗?非常感谢!

【问题讨论】:

  • = "abc" 应该是 == "abc"
  • @OhadEytan 谢谢!但是错误仍然相同:(
  • 建议尝试:'df['NewText'] = np.where(np.logical_and(df['Text1'] == "abc", df['Date1']
  • df['NewText'] = np.where((df['Text1'] =="abc" )& ((pd.to_datetime('today') -df['Date1'] ).dt.days

标签: python pandas datetime dataframe


【解决方案1】:

您的代码中有 3 个错误:

  1. 通过== operator 测试变量是否相等。
  2. 确保将各个条件括在avoid chained comparisons 中。
  3. 对于 90 天内的日期,请检查您的测试数据是否大于 days90

结合起来,下面的代码就可以工作了:

df['NewText'] = np.where((df['Text1'] == "abc") & (df['Date1'] > days90), "New", np.nan)

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2018-11-15
    • 2021-09-22
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 2016-07-05
    相关资源
    最近更新 更多