使用pandas从现有列添加新日期列

时间:2017-09-28 02:09:53

标签: python pandas datetime for-loop dataframe

我有一个日期和周的数据框,如下所示:

weeks = ["2016 W08","2016 W09","2016 W10","2016 W11"]
date = ["2-22-16", "2-29-16", "3-7-16", "3-14-16"]
df = pd.DataFrame(
{'week': weeks,
 'date': date,
 })
df
          date      week
0   2016-02-22  2016 W08
1   2016-02-29  2016 W09
2   2016-03-07  2016 W10
3   2016-03-14  2016 W11

我正在努力创建一个比end的值晚7天的新列date

我完全厌恶for循环,并且错过了如何遍历每个索引。

import datetime
for row in df['date']:
    start_date = df[row]
    df['end_date'] = start_date + datetime.timedelta(days = 7)

我知道我接近答案但却错过了!

2 个答案:

答案 0 :(得分:1)

from datetime import timedelta
df.date=pd.to_datetime(df.date)
df.date+timedelta(days=7)

Out[691]: 
0   2016-02-29
1   2016-03-07
2   2016-03-14
3   2016-03-21
Name: date, dtype: datetime64[ns]

如果你需要循环:

import datetime
for i,row in df.iterrows():
    df.loc[i,'new']= row['date'] + datetime.timedelta(days = 7)
df
Out[698]: 
        date      week        new
0 2016-02-22  2016 W08 2016-02-29
1 2016-02-29  2016 W09 2016-03-07
2 2016-03-07  2016 W10 2016-03-14
3 2016-03-14  2016 W11 2016-03-21

编辑:为什么你的循环不起作用

for row in df['date']:
    start_date = row
    print(start_date + datetime.timedelta(days=7))
此处

row返回date的值,您无法通过自己的值调用df值。

答案 1 :(得分:1)

尝试pd.DateOffset

<div class="menu-secondary-menu-links-container">

    <ul id="menu-secondary-menu-links" class="menu">
        <li id="menu-item-161" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-161"><a title="Our Programs" href="http://localhost/wordpress/courses/">Courses</a></li>
        <li id="menu-item-160" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-160"><a title="Event Schedule " href="http://localhost/wordpress/events/">Event Calendar</a></li>
        <li id="menu-item-159" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-159"><a title="Registration Open" href="http://localhost/wordpress/book-a-seminar/">Book A Seminar</a></li>
        <li id="menu-item-158" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-158"><a title="Registration Open" href="http://localhost/wordpress/book-a-workshop/">Book A Workshop</a></li>
    <li id="menu-item-293" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-293"><a href="http://localhost/wordpress/gallery/">Gallery</a></li>
</ul>
</div>

df将是:

import pandas as pd
weeks = ["2016 W08","2016 W09","2016 W10","2016 W11"]
date = ["2-22-16", "2-29-16", "3-7-16", "3-14-16"]
df = pd.DataFrame(
{'week': weeks,
 'date': date,
 })
df['date'] = pd.to_datetime(df['date']) #convert date column to datetime format
df['end_date'] = pd.DatetimeIndex(df['date']) + pd.DateOffset(7) #create new column end_date which is 7 days later
df