python pandas:如何循环数据框并添加列

时间:2014-02-25 00:22:10

标签: python pandas

我需要一个循环来执行此代码正在执行的操作并自动生成列ep1 ep2等等。

df['ep1'] = df.ep1.apply(lambda x: datetime.datetime(x.year,x.month,1))
df['ep2'] = df.ep1.apply(lambda x: datetime.datetime((x+datetime.timedelta(days=40)).year,(x+datetime.timedelta(days=40)).month,1))
df['ep3'] = df.ep2.apply(lambda x: datetime.datetime((x+datetime.timedelta(days=40)).year,(x+datetime.timedelta(days=40)).month,1))

其中ep向量是df.opdate和df.closdate之间的第一天。

作为开始

import pandas as pd
import datetime
d = {'closdate' : pd.Series([datetime.datetime(2014, 3, 2), datetime.datetime(2014, 2, 2)]),'opdate' : pd.Series([datetime.datetime(2014, 1, 1), datetime.datetime(2014, 1, 1)])}

df=pd.DataFrame(d)

df['ep1'] = df.opdate.apply(lambda x: x if x > datetime.datetime(2014,1,1) else datetime.datetime(2014,1,1))
df['ep1'] = df.ep1.apply(lambda x: datetime.datetime(x.year,x.month,1))
df['ep2'] = df.ep1.apply(lambda x: datetime.datetime((x+datetime.timedelta(days=40)).year,(x+datetime.timedelta(days=40)).month,1))
df['ep3'] = df.ep2.apply(lambda x: datetime.datetime((x+datetime.timedelta(days=40)).year,(x+datetime.timedelta(days=40)).month,1))

如何循环直到ep大于df.closdate?

1 个答案:

答案 0 :(得分:4)

使用where代替apply,并使用np.timedelta64

添加天数
import numpy as np
from pandas import Timestamp

months = range(1, 13)
df['ep0'] = df.opdate.where(df.opdate > Timestamp('20140101'), Timestamp('20140101'))
for month in months:
    colname = 'ep%d' % month
    prev_colname = 'ep%d' % (month - 1)
    df[colname] = df[prev_colname] + np.timedelta64(40, 'D')