python - 根据日期创建多个列

标签 python python-3.x pandas date dataframe

我最近开始使用 pandas,在使用“date”进行测试期间,我发现了这个挑战。给定这个数据框:

df = pd.DataFrame({'id': [123, 431, 652, 763, 234], '时间': ['8/1/2017', '6/1/2015', '7/1/2016', '9/1/2014', '12/1/2018']})

使用回溯日期列创建新的数据框,如下所示:

    id        time       time1       time2       time3       time4      time5
0   123 2017-08-01  2017-07-01  2017-06-01  2017-05-01  2017-04-01  2017-03-01
1   431 2015-06-01  2015-05-01  2015-04-01  2015-03-01  2015-02-01  2015-01-01
2   652 2016-07-01  2016-06-01  2016-05-01  2016-04-01  2016-03-01  2016-02-01
3   763 2014-09-01  2014-08-01  2014-07-01  2014-06-01  2014-05-01  2014-04-01
4   234 2018-12-01  2018-11-01  2018-10-01  2018-09-01  2018-08-01  2018-07-01

我尝试使用这些代码:

df['time'] = pd.to_datetime(df['time'], errors='coerce') #Object to Date 
df['time1'] = df['time'] - pd.DateOffset(months=1)
df['time2'] = df['time'] - pd.DateOffset(months=2)
df['time3'] = df['time'] - pd.DateOffset(months=3)
df['time4'] = df['time'] - pd.DateOffset(months=4)
df['time5'] = df['time'] - pd.DateOffset(months=5)

有没有办法更快、更有效地解决这个问题?我已经测试了几种创建回溯日期的方法。但是我不知道如何处理多列。因为如果数据需要回溯24个月,我就必须(手动)复制粘贴很多。

最佳答案

这是使用 date_rangeconcat 的一种方法

s=df.time.apply(lambda x : pd.date_range(end=x,periods =6,freq='MS')[::-1].tolist())
df=pd.concat([df,pd.DataFrame(s.tolist(),index=df.index).add_prefix('Time').iloc[:,1:]],axis=1)
df
    id       time      Time1      Time2      Time3      Time4      Time5
0  123 2017-08-01 2017-07-01 2017-06-01 2017-05-01 2017-04-01 2017-03-01
1  431 2015-06-01 2015-05-01 2015-04-01 2015-03-01 2015-02-01 2015-01-01
2  652 2016-07-01 2016-06-01 2016-05-01 2016-04-01 2016-03-01 2016-02-01
3  763 2014-09-01 2014-08-01 2014-07-01 2014-06-01 2014-05-01 2014-04-01
4  234 2018-12-01 2018-11-01 2018-10-01 2018-09-01 2018-08-01 2018-07-01

关于python - 根据日期创建多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54032552/

相关文章:

python - Matplotlib 使用一组特定数据点绘制等高线图

python - 在python中渲染图像以在html中显示

python - Python 3 namedtuple 子类中的 _asdict 返回空字典

python - Pyspark:是否有与 pandas info() 等效的方法?

python - Pandas 和 numpy 线程安全

python - 组合两个 pandas 数据框,使相同的列索引/标题彼此相邻

Python 子进程 : Print to stdin, 读取标准输出直到换行,重复

python - 比较 list 类型的 python 字典值以查看它们是否按该顺序匹配

Python Lambda 单位矩阵

Python pandas 从日期时间数组生成一个月的第一天