使用pandas将年份和月份列干净地组合到单个日期列

时间:2018-01-17 15:46:23

标签: python pandas date datetime dataframe

我的数据如下:

+----+------+-------+
| ID | YEAR | MONTH |
+----+------+-------+
| A  | 2017 |     1 |
| B  | 2017 |     2 |
| C  | 2017 |     3 |
| D  | 2017 |     4 |
| E  | 2017 |     5 |
| F  | 2017 |     6 |
+----+------+-------+

我想添加一个名为DATE的新列,该列存储由YEARMONTH列的日期对象组成的新列。像这样:

+----+------+-------+------------+
| ID | YEAR | MONTH |    DATE    |
+----+------+-------+------------+
| A  | 2017 |     1 | 2017-01-01 |
| B  | 2017 |     2 | 2017-02-01 |
| C  | 2017 |     3 | 2017-03-01 |
| D  | 2017 |     4 | 2017-04-01 |
| E  | 2017 |     5 | 2017-05-01 |
| F  | 2017 |     6 | 2017-06-01 |
+----+------+-------+------------+

我使用以下代码创建列,但想知道是否有更清洁的'Pythonic'单行。类似df['DATE']=date(df.year, df.month, 1)

的内容
import pandas as pd
from datetime import date


ID  = ['A', 'B', 'C', 'D', 'E', 'F']
YEAR = [2017, 2017, 2017, 2017, 2017, 2017]
MONTH = [1, 2, 3, 4, 5, 6]


df = pd.DataFrame({'ID': ID, 'YEAR': YEAR, 'MONTH': MONTH})


DATE = []
for y, m in zip(df.YEAR, df.MONTH):
    DATE.append(date(y, m, 1))


df['DATE'] = DATE

1 个答案:

答案 0 :(得分:2)

选项1
将包含3列的数据框切片 - YEARMONTHDAY传递给pd.to_datetime

df['DATE'] = pd.to_datetime(df[['YEAR', 'MONTH']].assign(DAY=1))
df

  ID  MONTH  YEAR       DATE
0  A      1  2017 2017-01-01
1  B      2  2017 2017-02-01
2  C      3  2017 2017-03-01
3  D      4  2017 2017-04-01
4  E      5  2017 2017-05-01
5  F      6  2017 2017-06-01

选项2
字符串连接,pd.to_datetime

pd.to_datetime(df.YEAR.astype(str) + '/' + df.MONTH.astype(str) + '/01')

0   2017-01-01
1   2017-02-01
2   2017-03-01
3   2017-04-01
4   2017-05-01
5   2017-06-01
dtype: datetime64[ns]