加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – DateOffset Panda减法

发布时间:2020-12-20 11:59:47 所属栏目:Python 来源:网络整理
导读:我有一个dataFrame [in] MyDates[out] 2017-04-04 -5.02017-04-03 -5.02017-03-31 -4.02017-03-30 -6.02017-03-29 -5.02017-03-28 -5.0 每个数字对应我应该在相应日期添加或删除的天数.我想创建一个新列,索引日期减去第一列中的天数.我知道我可以用DateOffse
我有一个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做到但我无法弄清楚如何…

谢谢!

解决方法

您可以将列转换为 TimedeltaIndexto_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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读