将日期操作应用于整个数据框

时间:2018-02-28 15:40:17

标签: python pandas

import pandas as pd
import numpy as np
df = pd.DataFrame({'year': np.repeat(2018,12), 'month': range(1,13)})

在这个数据框中,我有兴趣创建一个名为' year_month'这样每个值都是这样的:

datetime.date(df['year'][0], df['month'][0], 1).strftime("%Y%m")

我坚持如何将此操作应用于整个数据框,并希望得到任何帮助。

3 个答案:

答案 0 :(得分:3)

加入转换为string的两列和month添加zfill

df['new'] = df['year'].astype(str) + df['month'].astype(str).str.zfill(2)

或者按assign添加新列day,转换列to_datetime和上一个strftime

df['new'] = pd.to_datetime(df.assign(day=1)).dt.strftime("%Y%m")

如果DataFrame中有多列:

df['new'] = pd.to_datetime(df.assign(day=1)[['day','month','year']]).dt.strftime("%Y%m")
print (df)
    month  year     new
0       1  2018  201801
1       2  2018  201802
2       3  2018  201803
3       4  2018  201804
4       5  2018  201805
5       6  2018  201806
6       7  2018  201807
7       8  2018  201808
8       9  2018  201809
9      10  2018  201810
10     11  2018  201811
11     12  2018  201812

<强>计时

df = pd.DataFrame({'year': np.repeat(2018,12), 'month': range(1,13)})
df = pd.concat([df] * 1000, ignore_index=True)

In [212]: %timeit pd.to_datetime(df.assign(day=1)).dt.strftime("%Y%m")
10 loops, best of 3: 74.1 ms per loop

In [213]: %timeit df['year'].astype(str) + df['month'].astype(str).str.zfill(2)
10 loops, best of 3: 41.3 ms per loop

答案 1 :(得分:1)

一种方法是直接从源数据创建datetime对象:

import pandas as pd
import numpy as np
from datetime import date

df = pd.DataFrame({'date': [date(i, j, 1) for i, j \
                   in zip(np.repeat(2018,12), range(1,13))]})

#           date
# 0   2018-01-01
# 1   2018-02-01
# 2   2018-03-01
# 3   2018-04-01
# 4   2018-05-01
# 5   2018-06-01
# 6   2018-07-01
# 7   2018-08-01
# 8   2018-09-01
# 9   2018-10-01
# 10  2018-11-01
# 11  2018-12-01

答案 2 :(得分:0)

您可以使用应用功能,例如:

df['year_month'] = df.apply(lambda row: datetime.date(row[1], row[0], 1).strftime("%Y%m"), axis = 1)