【问题标题】:Python: Create new column that counts the days between current date and a lag datePython:创建新列,计算当前日期和滞后日期之间的天数
【发布时间】:2022-01-15 13:27:37
【问题描述】:

我想创建一个函数,将天数作为日期和日期之间的整数来计算(例如 df['new_col'] = (df['date'].shift(#periods) -df['date']). 日期变量是 datetime64[D]。 例如:df['report_date'].shift(39) = '2008-09-26' and df['report_date'] = '2008-08-18' and df['delta'] = 39.

import pandas as pd 
from datetime import datetime
from datetime import timedelta
import datetime as dt
dates =pd.Series(np.tile(['2012-08-01','2012-08-15','2012-09-01','2012-08-15'],4)).astype('datetime64[D]')
dates2 =pd.Series(np.tile(['2012-08-01','2012-09-01','2012-10-01','2012-11-01'],4)).astype('datetime64[D]')
stocks = ['A','A','A','A','G','G','G','G','B','B','B','B','F','F','F','F']
stocks = pd.Series(stocks)
df = pd.DataFrame(dict(stocks = stocks, dates = dates,report_date = dates2)).reset_index()
df.head()
print('df info:',df.info())

下面的代码是我最近尝试创建这个变量,但代码产生的结果不正确。

df['delta'] = df.groupby(['stocks','dates'])['report_date'].transform(lambda x: (x.shift(1).rsub(x).dt.days))

【问题讨论】:

  • 您的问题不清楚。你能用预期的输出更新你的帖子吗?
  • df.groupby(['stocks'])['report_date'].transform(lambda x: (x.shift(1).rsub(x).dt.days)) ?

标签: python pandas group-by


【解决方案1】:

我想出了使用 for 循环和 zip 函数的解决方案,像这样简单地减去每一对......

from datetime import datetime
import pandas as pd
 
dates = ['2012-08-01', '2012-08-15', '2012-09-01', '2012-08-15']
dates2 = ['2012-08-01', '2012-09-01', '2012-10-01', '2012-11-01']
diff = []

for i, x in zip(dates, dates2):
    i = datetime.strptime(i, '%Y-%m-%d')
    x = datetime.strptime(x, '%Y-%m-%d')
    diff.append(i - x)

df = {'--col1--': dates, '--col2--': dates2, '--difference--': diff}
df = pd.DataFrame(df)
print(df)

输出:

     --col1--    --col2-- --difference--
0  2012-08-01  2012-08-01         0 days
1  2012-08-15  2012-09-01       -17 days
2  2012-09-01  2012-10-01       -30 days
3  2012-08-15  2012-11-01       -78 days

Process finished with exit code 0

希望能解决你的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多