Python Pandas - 将字符串数据转换为 datetime 类型
要将字符串数据转换为实际日期,即 datetime 类型,请使用 to_datetime() 方法。首先,让我们创建一个包含 3 个类别的数据框,其中之一是日期字符串 -
dataFrame = pd.DataFrame({ 'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Chairs'],'Date_of_Purchase': ['10/07/2021','20/04/2021','25/06/2021','15/02/2021'], })
使用 to_datetime() 将日期字符串转换为实际日期 -
dataFrame['Date_of_Purchase'] = pd.to_datetime(dataFrame['Date_of_Purchase'])
示例
以下是完整的代码 -
import pandas as pd # create a dataframe dataFrame = pd.DataFrame({ 'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Stationery'],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Chairs'],'Date_of_Purchase': ['10/07/2021','20/04/2021','25/06/2021','15/02/2021'], }) print"\nDataFrame...\n",dataFrame # convert date strings to actual dates dataFrame['Date_of_Purchase'] = pd.to_datetime(dataFrame['Date_of_Purchase']) print"\nUpdated DataFrame (string dates converted to dates)...\n",dataFrame
输出
这将生成以下输出 -
DataFrame... Date_of_Purchase Product Category Product Name 0 10/07/2021 Computer Keyboard 1 20/04/2021 Mobile Phone Charger 2 25/06/2021 Electronics SmartTV 3 15/02/2021 Stationery Chairs Updated DataFrame (string dates converted to dates)... Date_of_Purchase Product Category Product Name 0 2021-10-07 Computer Keyboard 1 2021-04-20 Mobile Phone Charger 2 2021-06-25 Electronics SmartTV 3 2021-02-15 Stationery Chairs
广告