合并Pandas DataFrame DateTime列

2024-04-25 20:42:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有如下数据帧:

Year Month Day
2003 1     8
2003 2     7

如何在dataframe的新定义列中组合年、月和日,因此dataframe将是:

Year Month Day Date
2003 1     8   2003-1-8
2003 2     7   2003-2-7

你知道吗?

我正在使用pandas python数据框

谢谢!


Tags: 数据dataframepandasdate定义yeardaymonth
2条回答

最好使用^{}

df['Date'] = pd.to_datetime(df[['Year','Month','Day']])
>>> df
   Year  Month  Day       Date
0  2003      1    8 2003-01-08
1  2003      2    7 2003-02-07
>>> from datetime import datetime
>>> df['Date'] = df.apply(lambda row: datetime(
                              row['Year'], row['Month'], row['Day']), axis=1)
>>> df
   Year  Month  Day                Date
0  2003      1    8 2003-01-08 00:00:00
1  2003      2    7 2003-02-07 00:00:00

相关问题 更多 >