Pandas Python- can datetime be used with vectorized inputs

后端 未结 1 750
一生所求
一生所求 2021-01-26 11:10

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 fi

相关标签:
1条回答
  • 2021-01-26 11:25

    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
    
    0 讨论(0)
提交回复
热议问题