我有以下数据框。
日期是dtype='datetime64[ns, UTC]'
announce_date announce_time
0 2013-01-23 After Market Close
1 2013-04-23 Before Market Open
2 2013-07-20 After Market Close
如何创建新的偏移量列
如果announce_date
是announce_time
,则"After Market Close"
乘以1。
announce_date announce_time impact_date
0 2013-01-23 After Market Close 2013-01-24
1 2013-04-23 Before Market Open 2013-04-23
2 2013-07-20 After Market Close 2013-07-21
我可以做一个偏移日期列,但还没有弄清楚如何应用该条件。
import pandas as pd
df['impact_date'] = df['announce_date'] + pd.DateOffset(days=1)
答案 0 :(得分:3)
使用pd.to_timedelta
生成布尔掩码并从其生成偏移量。
# Convert "announce_date" to datetime if not already done.
# df['announce_date'] = pd.to_datetime(df['announce_date'], errors='coerce')
# Now calculate the offset.
offset = pd.to_timedelta(
df['announce_time'].eq("After Market Close").astype(int), unit='D')
df['impact_date'] = df['announce_date'] + offset
print(df)
announce_date announce_time impact_date
0 2013-01-23 After Market Close 2013-01-24
1 2013-04-23 Before Market Open 2013-04-23
2 2013-07-20 After Market Close 2013-07-21
答案 1 :(得分:1)
您可以使用np.where
df ['impact_date'] = df ['announce_date'] + np.where(df ['announce_time'] ==“收市后”,pd.DateOffset(天= 1),pd.DateOffset(天= 0))
This answer有详细说明。
答案 2 :(得分:1)
您可以像这样创建遍历announce_time的while循环...
count = 0
list1 = []
while count != len(df):
if df.iloc[count,1] == 'After Market Close':
list1.append(df.iloc[count,0] + pd.DateOffset(days=1))
count += 1
else:
list1.append(df.iloc[count,0])
count += 1
df['impact_date'] = list1