Pandas Python-可以将日期时间与矢量化输入配合使用 [英] Pandas Python- can datetime be used with vectorized inputs
本文介绍了Pandas Python-可以将日期时间与矢量化输入配合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的熊猫数据框的前三列中包含年,月和日.为了将它们转换为日期时间类型,我使用了一个for循环,该循环遍历每一行,将每一行的前3列中的内容作为datetime函数的输入.我有什么办法可以避免此处的for循环并将日期作为日期时间?
My pandas dataframe has year, month and date in the first 3 columns. To convert them into a datetime type, i use a for loop that loops over each row taking the content in the first 3 columns of each row as inputs to the datetime function. Any way i can avoid the for loop here and get the dates as a datetime?
推荐答案
我不确定是否存在矢量化挂钩,但是无论如何您都可以使用apply
:
I'm not sure there's a vectorized hook, but you can use apply
, anyhow:
>>> df = pd.DataFrame({"year": [1992, 2003, 2014], "month": [2,3,4], "day": [10,20,30]})
>>> df
day month year
0 10 2 1992
1 20 3 2003
2 30 4 2014
>>> df["Date"] = df.apply(lambda x: pd.datetime(x['year'], x['month'], x['day']), axis=1)
>>> df
day month year Date
0 10 2 1992 1992-02-10 00:00:00
1 20 3 2003 2003-03-20 00:00:00
2 30 4 2014 2014-04-30 00:00:00
这篇关于Pandas Python-可以将日期时间与矢量化输入配合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文