我有一个包含一些时间戳的数据帧。我试图找到某些不满足条件的时间戳,并根据另一个时间戳和正在测试的当前时间戳的片段来计算它们的新时间戳值。
df = pd.DataFrame(data={'col1': [pd.Timestamp(2021, 1, 1, 12), pd.Timestamp(2021, 1, 2,
12), pd.Timestamp(2021, 1, 3, 12)],
'col2': [pd.Timestamp(2021, 1, 4, 12), pd.Timestamp(2021, 1, 5,
12), pd.Timestamp(2021, 1, 6, 12)]})
print(df)
# col1 col2
# 0 2021-01-01 12:00:00 2021-01-04 12:00:00
# 1 2021-01-02 12:00:00 2021-01-05 12:00:00
# 2 2021-01-03 12:00:00 2021-01-06 12:00:00
我正在尝试做这样的事情:
testDate = pd.Timestamp(2021, 1, 2, 16)
df['newCol'] = df['col1'].where(df['col1'].dt.date <= testDate.date(), pd.Timestamp(year=testDate.year, month=testDate.month, day=testDate.day, hour=df['col1'].dt.hour))
我收到一个关于歧义的错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
如果我删除最后一位
hour=df['col1'].dt.hour
,代码将会运行,所以我知道它与此有关,但我不明白为什么它会抱怨真实性,因为那一小段代码没有测试任何条件,这只是分配。我认为这是因为我试图使用正在迭代的值来计算新值,但如果我使用整数而不是时间戳尝试此过程,它运行得很好:
df = pd.DataFrame(data={'col1': [1,2,3], 'col2': [4,5,6]})
print(df)
# col1 col2
# 0 1 4
# 1 2 5
# 2 3 6
testInt = 2
df['newCol'] = df['col1'].where(df['col1'] < testInt, df['col1'] + 2)
print(df)
# col1 col2 newCol
# 0 1 4 1
# 1 2 5 4
# 2 3 6 5
做我想做的事情的正确方法是什么?
您必须先创建目标系列:
target = (pd.Series(testDate.normalize(), index=df.index)
+ (df['col1'] - df['col1'].dt.normalize()))
df['newCol'] = df['col1'].where(df['col1'] <= testDate, target)
输出:
>>> df
col1 col2 newCol
0 2021-01-01 12:00:00 2021-01-04 12:00:00 2021-01-01 12:00:00
1 2021-01-02 12:00:00 2021-01-05 12:00:00 2021-01-02 12:00:00
2 2021-01-03 12:00:00 2021-01-06 12:00:00 2021-01-02 12:00:00
>>> target
0 2021-01-02 12:00:00
1 2021-01-02 12:00:00
2 2021-01-02 12:00:00
dtype: datetime64[ns]