我有一个dataFrame
[in] MyDates
[out]
2017-04-04 -5.0
2017-04-03 -5.0
2017-03-31 -4.0
2017-03-30 -6.0
2017-03-29 -5.0
2017-03-28 -5.0
每个数字对应我应该在相应日期添加或删除的天数.我想创建一个新列,索引日期减去第一列中的天数.我知道我可以用DateOffset做到但我无法弄清楚如何…
谢谢!
最佳答案 您可以将列转换为
TimedeltaIndex
或
to_timedelta
并添加()或减去( – )值:
df['new'] = df.index - pd.TimedeltaIndex(df['col'], unit='d')
print (df)
col new
2017-04-04 -5.0 2017-04-09
2017-04-03 -5.0 2017-04-08
2017-03-31 -4.0 2017-04-04
2017-03-30 -6.0 2017-04-05
2017-03-29 -5.0 2017-04-03
2017-03-28 -5.0 2017-04-02
要么:
df['new'] = df.index + pd.to_timedelta(df['col'], unit='d')
print (df)
col new
2017-04-04 -5.0 2017-03-30
2017-04-03 -5.0 2017-03-29
2017-03-31 -4.0 2017-03-27
2017-03-30 -6.0 2017-03-24
2017-03-29 -5.0 2017-03-24
2017-03-28 -5.0 2017-03-23
如果Series as input添加to_frame
:
df = s.to_frame('date')
df['new'] = df.index - pd.TimedeltaIndex(df['date'], unit='d')
print (df)
date new
2017-04-04 -5.0 2017-04-09
2017-04-03 -5.0 2017-04-08
2017-03-31 -4.0 2017-04-04
2017-03-30 -6.0 2017-04-05
2017-03-29 -5.0 2017-04-03
2017-03-28 -5.0 2017-04-02