Python 从2个浮点列创建datetime列
我正在尝试将两个float列组合成一个数据帧中的datetime列。例如,列year的值为Python 从2个浮点列创建datetime列,python,pandas,datetime,dataframe,Python,Pandas,Datetime,Dataframe,我正在尝试将两个float列组合成一个数据帧中的datetime列。例如,列year的值为2018.0,列month的值为1.0,我希望datetime中的输出为1/1/2018 有没有一种有效的方法可以做到这一点?您可以在分配了日之后将数据帧馈送到: df = pd.DataFrame([[2018.0, 1.0], [2017.0, 5.0], [2019, 3.0], [2017, 12.0]], columns=['year', 'month'])
2018.0
,列month的值为1.0
,我希望datetime中的输出为1/1/2018
有没有一种有效的方法可以做到这一点?您可以在分配了
日之后将数据帧馈送到:
df = pd.DataFrame([[2018.0, 1.0], [2017.0, 5.0], [2019, 3.0], [2017, 12.0]],
columns=['year', 'month'])
df['datetime'] = pd.to_datetime(df.assign(day=1))
print(df)
year month datetime
0 2018.0 1.0 2018-01-01
1 2017.0 5.0 2017-05-01
2 2019.0 3.0 2019-03-01
3 2017.0 12.0 2017-12-01
注意:这依赖于严格的命名约定:年
,月
,日
是可接受的组合。如有必要,您可以通过重命名列。您尝试了什么?带有floar的列的名称为“IncMth”和“IncYr”。我试图转换为字符串df[“IncMth”].astype(int)+“/1/”+df['IncYr'].apply(str).str[0:4],然后应用to_datetime函数。另外,尝试将浮动引入datetime.date功能(datetime.date(df['IncYr',df['IncMth]],1),但这不起作用。当然这里可能有一个简单的解决方案哇,我更喜欢你的解决方案。感谢分享:)