【发布时间】: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