Pandas Python- can be used as time with vectorized inputs

My pandas dataframe has year, month and date in the first three columns. To convert them to a datetime type, I use a for loop that traverses each row, occupying the contents in the first three columns of each row as input for the datetime function. Anyway, can I avoid the for loop and get dates as datetime?

0
source share
1 answer

I'm not sure there is a vector hook, but you can use applyone way or another:

>>> 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
+1
source

Source: https://habr.com/ru/post/1538668/


All Articles